#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;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
hMutex=CreateMutex(NULL,FALSE,"MutexName");
//FALSE是创建的mutex不属于任何一个进程,每个mutex里有一个计数器,记录
//当前mutex所属的进程的调用次数
Sleep(4000); //主线程结束,其他的线程也要结束,故在此停留,把执行机会留给其他的子线程 }
DWORD WINAPI Fun1Proc( LPVOID lpParameter )
{ while(TRUE) {
WaitForSingleObject(hMutex,INFINITE);
//当计数器为0时,mutex的进程id标示为fun1进程,计数器为1
if(tickets>0) {
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else break;
ReleaseMutex(hMutex); //释放mutex,计数器值减1,此时为0
}
cout<<"thread1 is running"<<endl;
return 0;
}
DWORD WINAPI Fun2Proc( LPVOID lpParameter ) {
while(TRUE) {
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0) {
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
cout<<"thread2 is running"<<endl;
return 0;
}