先上代碼吧://這是2個(gè)線程模擬賣火車票的小程序#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;//創(chuàng)建線程hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);CloseHandle(hThread1);CloseHandle(hThread2);//創(chuàng)建互斥對(duì)象hMutex=CreateMutex(NULL,TRUE,_T("tickets"));//創(chuàng)建互斥體 一次運(yùn)行一個(gè)線程if (hMutex){if (ERROR_ALREADY_EXISTS==GetLastError()){cout<<"only one instance can run!"<<endl;return;}}WaitForSingleObject(hMutex,INFINITE);//等待進(jìn)入互斥體 INFINITE -1ReleaseMutex(hMutex);ReleaseMutex(hMutex);Sleep(3000);}//線程1的入口函數(shù)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的入口函數(shù)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;}在上面的代碼是一個(gè)多線程的模型,但這個(gè)模型中有一個(gè)很有趣的地方:原始作者用WaitForSingleObject(hMutex,INFINITE);語(yǔ)句來(lái)獲得互斥體,同時(shí)用ReleaseMutex(hMutex);語(yǔ)句來(lái)釋放互斥體,但仔細(xì)看代碼卻可以發(fā)現(xiàn),每一個(gè)WaitForSingleObject其實(shí)是對(duì)應(yīng)了兩句一摸一樣的釋放語(yǔ)句,看上去好像是每獲得一次互斥體就要釋放兩遍一樣。
刪除其中的一句ReleaseMutex,但發(fā)現(xiàn)這樣做會(huì)導(dǎo)致互斥體不能被正常釋放。請(qǐng)問(wèn)這是怎么回事?
慕尼黑5688855
2023-03-02 14:10:57