MFC学习 多线程

时间:2022-05-08 18:18:26
#include <Windows.h>
#include <process.h>
#include <stdio.h> HANDLE hMutex; //互斥对象
void ProcessTask(void * args)
{
int a = ;
WaitForSingleObject(hMutex, INFINITE);
while ( a < )
printf("_beginthread %d\n", a++);
ReleaseMutex(hMutex);
//结束后会自动调用_endtrhead
}
unsigned int _stdcall ProcessTask2(void * args)
{
int a = ;
WaitForSingleObject(hMutex, INFINITE);
while ( a < )
printf("_beginthreadex %d\n", a++);
ReleaseMutex(hMutex); //如果不释放, 线程结束时, 系统也会释放
//结束后会自动调用_endtrheadex
return ;
}
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
int a = ;
WaitForSingleObject(hMutex, INFINITE);
while ( a < )
printf("CreateThread %d\n", a++);
ReleaseMutex(hMutex);
return ;
} int main()
{
hMutex = CreateMutex(NULL, FALSE, "tickets");
if(hMutex)
{
if(ERROR_ALREADY_EXISTS == GetLastError())
{
printf("one instance has exist\n");
system("pause");
return ;
}
}
_beginthread(ProcessTask, , );
_beginthreadex(NULL, , ProcessTask2, NULL, , );
Sleep();
DWORD threadId;
HANDLE hThread3 = CreateThread(, , ThreadProc, , , &threadId); //不建议使用, 在处理c库的时间类函数会内在泄漏大约70-80字节
//创建匿名互斥对象
//hMutex = CreateMutex(NULL, FALSE, NULL); //第二个参数参数初始化时当前线是否拥有互斥对象, 如果设置发TRUE, 可以用ReleaseMutex释放
//创建一个命名互斥对象可以判断实例是否在运行 CloseHandle(hThread3);
system("pause");
return ;
}

代码下载