Windows的互斥鎖Mutex是能夠在進程間使用的,CreateMutex時能夠指定一個mutex名稱,此名稱能夠被其餘進程或線程使用。CreateMutex的第二個參數BOOL bInitialOwner表示在建立後是否是馬上獲取此鎖,至關於當即WaitForSingleObjectios
測試代碼:windows
#include <stdio.h>
#include <windows.h>
#include <iostream>
using namespace std;測試
int main()
{
HANDLE hmutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXT("MutexTest"));//打開進程鎖
if (hmutex == NULL)
{
cout<<"Create Mutex"<<endl;
hmutex = CreateMutex(NULL, false, TEXT("MutexTest"));//建立進程鎖
}
DWORD ts = WaitForSingleObject(hmutex, INFINITE);//獲取進程鎖
if (WAIT_OBJECT_0 == ts)
{
for (int i=0; i<10; i++)
{
cout<<i<<endl;
Sleep(1000);
}
}
ReleaseMutex(hmutex);
if (hmutex != NULL){
CloseHandle(hmutex);
}
return 0;
}spa
測試結果:線程
只有窗口1執行完畢釋放鎖後,窗口2才能獲取到鎖,進行下一步的相應操做。進程
有不足的地方但願你們指出,我會驗證更新,一塊兒進步。it