版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/txwtech/article/details/88816695
MFC互斥对象实现多线程同步实例
// vs23_5_9.cpp : 定义控制台应用程序的入口点。
//txwtech
#include "stdafx.h"
#include "windows.h"
DWORD WINAPI ThreadProc1(LPVOID lpParam);
DWORD WINAPI ThreadProc2(LPVOID lpParam);
int iGolbalCount=0;
int iMax=12;
HANDLE hMutex;
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1,hThread2;
hThread1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
hThread2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
hMutex=CreateMutex(NULL,true,LPCTSTR("iGobalCount"));
//hMutex=CreateMutex(NULL,false,LPCTSTR("iGobalCount"));
if(hMutex==NULL)
{
printf("创建互斥对象失败\r\n");
return 0;
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(10000);
//CloseHandle(hThread1);
// CloseHandle(hThread2);
printf("主线程结束!");
Sleep(5000);
return 0;
}
DWORD WINAPI ThreadProc1(LPVOID lpParam)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if(iGolbalCount<iMax)
printf("这里是线程1,iGolbalCount=%d\r\n",iGolbalCount++);
else
break;
ReleaseMutex(hMutex);
Sleep(500);
}
return 0;
}
DWORD WINAPI ThreadProc2(LPVOID lpParam)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if(iGolbalCount<iMax)
printf("这里是线程2,iGolbalCount=%d\r\n",iGolbalCount++);
else
break;
ReleaseMutex(hMutex);
Sleep(500);
}
return 0;
}