代码程序进程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;
}