#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParameter
);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hMutex=CreateMutex(NULL,TRUE,NULL);//FALSE意思为没有被占用,有信号状态 +1
WaitForSingleObject(hMutex,INFINITE);// +1
ReleaseMutex(hMutex);// -1
ReleaseMutex(hMutex);// -1
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(4000);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);//放弃执行权利另一个线程运行
cout<<"thread1sell the ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2sell the ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
//////////////////
关于WaitForSingleObject(hMutex,INFINITE);内部会有一个计数器,根据申请或者释放自行加减1
hMutex=CreateMutex(NULL,TRUE,NULL);若设置为TRUE,申请同时就被主线程占用。
hMutex=CreateMutex(NULL,FALSE,NULL);若设置为FALSE,则申请后不被占用。
上文例子中的计数器加减情况如下。
hMutex=CreateMutex(NULL,TRUE,NULL);//FALSE意思为没有被占用,有信号状态+1
WaitForSingleObject(hMutex,INFINITE);// +1
ReleaseMutex(hMutex);// -1
ReleaseMutex(hMutex);// -1
由于上述例子中,waitforsingleobject是放在主线程上,所以线程Fun1Proc和Fun2Proc必须要在主线程的计数器为0的时候才能申请到“位置”,若不为零,不可以轮到1,2执行。