本文共 1372 字,大约阅读时间需要 4 分钟。
http://blog.csdn.net/riyuedangkong1/article/details/52462057
- #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);
- 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;
- }