#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI threadOneFunc(LPVOID param);
DWORD WINAPI threadTwoFunc(LPVOID param);
HANDLE mutex;//互斥对象(拥有线程ID和引用计数)
int tickets=100;
int main()
{
HANDLE threadOne=CreateThread(NULL,0,threadOneFunc,NULL,0,NULL);
HANDLE threadTwo=CreateThread(NULL,0,threadTwoFunc,NULL,0,NULL);
CloseHandle(threadOne);
CloseHandle(threadTwo);
mutex=CreateMutex(NULL,false,NULL);//互斥对象的所有权不属于自己
Sleep(5000);
return 0;
}
DWORD WINAPI threadOneFunc(LPVOID param)
{
while(true)
{
WaitForSingleObject(mutex,INFINITE);
if(tickets>0)
{
cout<<"one:"<<tickets--<<endl;
}
else
{
break;
}
ReleaseMutex(mutex);
}
return 0;
}
DWORD WINAPI threadTwoFunc(LPVOID param)
{
while(true)
{
WaitForSingleObject(mutex,INFINITE);
if(tickets>0)
{
cout<<"two:"<<tickets--<<endl;
}
else
{
break;
}
ReleaseMutex(mutex);
}
return 0;
}
线程互斥对象拥有一个线程ID和引用计数,只准线程的ID和互斥对象拥有的ID相同的时候才可以释放该互斥对象。