多執行緒之互斥鎖(By C++)與多程序
阿新 • • 發佈:2019-02-06
#include<Windows.h> #include<iostream> using namespace std; //互斥鎖 HANDLE hMutex1; HANDLE hMutex2; int flag; DWORD WINAPI MyThread2(LPVOID lpParamter) { while (1) { WaitForSingleObject(hMutex1,INFINITE); flag=!flag; cout << "MyThread1 Runing :"<<"執行緒1"<<" "<<flag<< endl; Sleep(1000); //此時鎖2被鎖,無法在下面解鎖1 WaitForSingleObject(hMutex2,INFINITE); ReleaseMutex(hMutex2); ReleaseMutex(hMutex1); } } DWORD WINAPI MyThread1(LPVOID lpParamter) { while (1) { WaitForSingleObject(hMutex2,INFINITE); flag=!flag; cout << "MyThread2 Runing"<<"執行緒1" <<" "<<flag<< endl; Sleep(1000); //此時鎖1被鎖,無法在下面解鎖2 WaitForSingleObject(hMutex1,INFINITE); ReleaseMutex(hMutex1); ReleaseMutex(hMutex2); } } int main() { //建立一個鎖 hMutex1 =CreateMutex(NULL,FALSE,NULL); hMutex2=CreateMutex(NULL,FALSE,NULL); HANDLE hThread1 = CreateThread(NULL, 0, MyThread1, NULL, 0, NULL); CloseHandle(hThread1); HANDLE hThread2 = CreateThread(NULL, 0, MyThread2,NULL, 0, NULL); CloseHandle(hThread2); while(1); return 0; }