版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/txwtech/article/details/88815803
MFC信号量对象实现多线程范例
// vs23_5_7.cpp : 定义控制台应用程序的入口点。
//txwtech vs2010
#include "stdafx.h"
#include "windows.h"
DWORD WINAPI ThreadProc1(LPVOID lpParam);
DWORD WINAPI ThreadProc2(LPVOID lpParam);
int iGolbalCount=0;
int iMax=12;
int cMax=1;
HANDLE hSemaphore;
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1,hThread2;
// hSemaphore=CreateSemaphore(NULL,cMax,iMax,NULL);//
hSemaphore=CreateSemaphore(NULL,cMax,cMax,NULL);
if(hSemaphore==NULL)
{
printf("创建信号量对象失败");
return 0;
}
hThread1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
hThread2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
Sleep(50000);
printf("主线程结束\n");
Sleep(30000);
return 0;
}
DWORD WINAPI ThreadProc1(LPVOID lpParam)
{
long count;
while(true)
{
DWORD dwWaitResult=WaitForSingleObject(hSemaphore,0L);//等待时间太短
//DWORD dwWaitResult=WaitForSingleObject(hSemaphore,INFINITE);//无限等待
if(dwWaitResult==WAIT_OBJECT_0)
{
if(iGolbalCount<iMax)
{
printf("这里是线程1,iGolbalCount=%d\r\n",iGolbalCount++);
//ReleaseSemaphore(hSemaphore,1,NULL);
ReleaseSemaphore(hSemaphore,1,&count);
}
else
{
//ReleaseSemaphore(hSemaphore,1,NULL);
ReleaseSemaphore(hSemaphore,1,&count);
break;
}
}
Sleep(500);//休眠时间很关键
}
return 0;
}
DWORD WINAPI ThreadProc2(LPVOID lpParam)
{
long count;
while(true)
{
// DWORD dwWaitResult=WaitForSingleObject(hSemaphore,INFINITE);
DWORD dwWaitResult=WaitForSingleObject(hSemaphore,0L);
if(dwWaitResult==WAIT_OBJECT_0)
{
if(iGolbalCount<iMax)
{
printf("这里是线程2,iGolbalCount=%d\r\n",iGolbalCount++);
//ReleaseSemaphore(hSemaphore,1,NULL);
ReleaseSemaphore(hSemaphore,1,&count);
}
else
{
//ReleaseSemaphore(hSemaphore,1,NULL);
ReleaseSemaphore(hSemaphore,1,&count);
break;
}
}
Sleep(500);
}
return 0;
}