代碼程序進程1:
#include<iostream>
#include <Windows.h>
#include <process.h>//使用進程
using namespace std;
HANDLE hMutex;//定義一個句柄給互斥對象使用
DWORD WINAPI Mythread(LPVOID lp1)
{
char ct1;
WaitForSingleObject(hMutex,INFINITE);
cout<<"Get Mutex"<<endl;
cout<<"Please input the control charater:";
while(1)
{
cin>>ct1;
if(ct1=='q'||ct1=='Q')
{
cout<<"Finished"<<endl;
break;
}
else
cout<<"Please input again:"<<endl;
}
ReleaseMutex(hMutex);
cout<<"Release the Mutex"<<endl;
cout<<"Come to your turn:"<<endl;
return 0;
}
int main(int argc,char* argv[])
{
HANDLE hHandle;
DWORD dw1;
hMutex=CreateMutex(NULL,
FALSE,
"MyMutexObject");//有名的互斥對象,可用於進程間的同步
//檢查互斥變量是否創建成功,嚴格;來說,每次都要在程序中檢查這種
if(hMutex==NULL)
{
cout<<"CreateMutex error :"<<GetLastError();
CloseHandle(hMutex);//關閉互斥變量的句柄
}
else
{
if(GetLastError()==ERROR_ALREADY_EXISTS)
{
cout<<"Mutex has been created!"<<endl;
}
else
{
cout<<"createMutex successfully"<<endl;
}
hHandle=CreateThread(NULL,0,Mythread,NULL,0,&dw1);
cout<<"create worker handle"<<endl;
}
Sleep(70000);
CloseHandle(hHandle);
CloseHandle(hMutex);
return 0;
}
進程2:
include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
HANDLE hMutex;
DWORD WINAPI MyThread(LPVOID lp)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"Get the Mutex"<<endl;
cout<<"Hello!everyone come to my turn"<<endl;
ReleaseMutex(hMutex);
cout<<"Release the mutex"<<endl;
return 0;
}
int main(int argc,char *argv[])
{
DWORD dw;
hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"MyMutexObject");
if(hMutex==NULL)
{
cout<<"OpenMutex error:"<<endl;
CloseHandle(hMutex);
}
else
{
if (GetLastError()==ERROR_ALREADY_EXISTS)
{
cout<<"Mutex has been opened"<<endl;
}
else
cout<<"Open Mutex successfully"<<endl;
HANDLE hHandle=CreateThread(NULL,0,MyThread,NULL,0,&dw);
CloseHandle(hHandle);//得把句柄關閉放在這兒,不然會提示句柄沒有初始化
cout<<"create worker Mutex "<<endl;
}
Sleep(70000);//把時間用的很長,便於操作得到反應
CloseHandle(hMutex);
//CloseHandle();
return 0;
}