#include<iostream> #include<Windows.h> using namespace std; int tickets=100; //火车票总数 HANDLE hSemaphore; DWORD WINAPI Thread1Proc(LPVOID lpParameter);//进程函数 DWORD WINAPI Thread2Proc(LPVOID lpParameter);//进程函数 void main() { HANDLE hThread1; HANDLE hThread2; hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL); //创建线程 hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL); hSemaphore=CreateSemaphore(NULL,1,1,NULL); //创建信号量,初始为1,最多为1 CloseHandle(hThread1); //释放句柄 CloseHandle(hThread2); CloseHandle(hSemaphore); while(TRUE) { WaitForSingleObject(hSemaphore,INFINITE); if(tickets>0) { cout<<"主线程卖出第"<<tickets--<<"张票"<<endl; Sleep(50); ReleaseSemaphore(hSemaphore,1,NULL); } else { ReleaseSemaphore(hSemaphore,1,NULL); //释放信号量资源 break; } } ExitThread(0); } DWORD WINAPI Thread1Proc(LPVOID lpParameter) { while(TRUE) { WaitForSingleObject(hSemaphore,INFINITE);//申请信号量 if(tickets>0) { cout<<"线程一卖掉第"<<tickets--<<"张票"<<endl; Sleep(50); ReleaseSemaphore(hSemaphore,1,NULL); } else { ReleaseSemaphore(hSemaphore,1,NULL); break; } } return 0; } DWORD WINAPI Thread2Proc(LPVOID lpParameter) { while(TRUE) { WaitForSingleObject(hSemaphore,INFINITE); if(tickets>0) { cout<<"线程二卖出第"<<tickets--<<"张票"<<endl; Sleep(50); ReleaseSemaphore(hSemaphore,1,NULL); } else { ReleaseSemaphore(hSemaphore,1,NULL); break; } } return 0; }