对于普通的线程间互斥可以使用CreateMutex传建一个匿名的互斥量做互斥,对进程间的互斥就要用到命名互斥量来做互斥了。用到的函数有:
1. 创建一个命名互斥量使用CreateMutex()方法,只需把lpName参数设置为非NULL,如"my mutex"
HANDLE WINAPI CreateMutex(
__in LPSECURITY_ATTRIBUTES lpMutexAttributes,
__in BOOL bInitialOwner,
__in LPCTSTR lpName );
2. 打开一个命名互斥量使用OpenMutex()方法,我们也需要对其中的lpName参数指定内容,如"my mutex"
HANDLE WINAPI OpenMutex(
__in DWORD dwDesiredAccess,
__in BOOL bInheritHandle,
__in LPCTSTR lpName );
下面给出两段代码,可以同时使用两个process1或process1和process2查看运行效果
进程1的代码:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
/*
SECURITY_ATTRIBUTES att;
att.nLength = sizeof(SECURITY_ATTRIBUTES );
att.lpSecurityDescriptor = NULL;
att.bInheritHandle = TRUE;
*/
HANDLE hMutex = CreateMutex(NULL, false, "pmutex");
if(NULL == hMutex)
{
cout<<"create mutex error "<<GetLastError()<<endl;
return 0;
}
else
{
cout<<" create mutex success:"<<hMutex<<endl;
}
for(int i = 0;i<10; i++)
{
DWORD d = WaitForSingleObject(hMutex, INFINITE);
if(WAIT_OBJECT_0 == d)
{
cout<<"begin sleep"<<endl;
Sleep(2000);
cout<<"process 1"<<endl;
if(ReleaseMutex(hMutex)!=0)
{
cout<<"reslease ok"<<endl;
}
else
{
cout<<"reslease failed"<<endl;
}
}
if(WAIT_ABANDONED == d)
{
cout<<"WAIT_ABANDONED"<<endl;
}
if(WAIT_FAILED ==d)
{
cout<<"mutex error"<<endl;
}
Sleep(2000);
}
CloseHandle(hMutex);
return 0;
}
进程2 process2的代码
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, false, "pmutex");
if(NULL == hMutex)
{
cout<<"open mutex error "<<GetLastError()<<endl;
return 0;
}
else
{
cout<<"open mutex success:"<<hMutex<<endl;
}
for(int i = 0;i<10; i++)
{
DWORD d = WaitForSingleObject(hMutex, INFINITE);
if(WAIT_OBJECT_0 == d)
{
cout<<"begin sleep"<<endl;
Sleep(2000);
cout<<"process 1"<<endl;
if(ReleaseMutex(hMutex)!=0)
{
cout<<"reslease ok"<<endl;
}
else
{
cout<<"reslease failed"<<endl;
}
}
if(WAIT_ABANDONED == d)
{
cout<<"WAIT_ABANDONED"<<endl;
}
if(WAIT_FAILED ==d)
{
cout<<"mutex error"<<endl;
}
Sleep(2000);
}
CloseHandle(hMutex);
return 0;
}