先上代碼吧://這是2個線程模擬賣火車票的小程序#include <windows.h>#include <iostream>#include <tchar.h>using namespace std;DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread dataDWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread dataint index=0;int tickets=10;HANDLE hMutex;void main(){HANDLE hThread1;HANDLE hThread2;//創建線程hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);CloseHandle(hThread1);CloseHandle(hThread2);//創建互斥對象hMutex=CreateMutex(NULL,TRUE,_T("tickets"));//創建互斥體 一次運行一個線程if (hMutex){if (ERROR_ALREADY_EXISTS==GetLastError()){cout<<"only one instance can run!"<<endl;return;}}WaitForSingleObject(hMutex,INFINITE);//等待進入互斥體 INFINITE -1ReleaseMutex(hMutex);ReleaseMutex(hMutex);Sleep(3000);}//線程1的入口函數DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data{while (true){ReleaseMutex(hMutex);WaitForSingleObject(hMutex,INFINITE);if (tickets>0){Sleep(500);cout<<"thread1 sell ticket :"<<tickets--<<endl;}elsebreak;ReleaseMutex(hMutex);}return 0;}//線程2的入口函數DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data{while (true){ReleaseMutex(hMutex);WaitForSingleObject(hMutex,INFINITE);if (tickets>0){Sleep(500);cout<<"thread2 sell ticket :"<<tickets--<<endl;}elsebreak;ReleaseMutex(hMutex);}return 0;}在上面的代碼是一個多線程的模型,但這個模型中有一個很有趣的地方:原始作者用WaitForSingleObject(hMutex,INFINITE);語句來獲得互斥體,同時用ReleaseMutex(hMutex);語句來釋放互斥體,但仔細看代碼卻可以發現,每一個WaitForSingleObject其實是對應了兩句一摸一樣的釋放語句,看上去好像是每獲得一次互斥體就要釋放兩遍一樣。
刪除其中的一句ReleaseMutex,但發現這樣做會導致互斥體不能被正常釋放。請問這是怎么回事?
慕尼黑5688855
2023-03-02 14:10:57