CreateMutex()//创建一个互斥体,已经存在会直接返回句柄 OpenMutex()//打开一个互斥体 WaitForSingleObject()//尝试加锁 ReleaseMutex()//解锁 进程间互斥通过互斥锁的名称进行
//进程1
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <windows.h>
using namespace std;
class MyClass
{
public:
MyClass(string lockName)
{
name= lockName;
};
~MyClass()
{
CloseHandle(hMutex);
hMutex = NULL;
};
void Lock()
{
hMutex = CreateMutex(NULL, false, name.c_str());
while (WaitForSingleObject(hMutex, INFINITE) != WAIT_OBJECT_0)
{
Sleep(1);
};
}
void UnLock()
{
hMutex = CreateMutex(NULL, false, name.c_str());
ReleaseMutex(hMutex);
}
private:
HANDLE hMutex;
string name;
};
static MyClass* myLock = new MyClass("mypmutex");
string GetTime()
{
SYSTEMTIME sys;
GetLocalTime(&sys);
char temp[256];
char name[256];
sprintf(temp, "%4d-%02d-%02d %02d:%02d:%02d-",
sys.wYear, sys.wMonth,
sys.wDay, sys.wHour,
sys.wMinute, sys.wSecond);
std::string inStr;
inStr += temp;
return inStr;
}
int main()
{
for (int i = 0;i < 10; i++)
{
myLock->Lock();
cout << GetTime() << "begin sleep" << endl;
Sleep(5000);
cout << GetTime() << "process 2222222222222222222" << endl;
myLock->UnLock();
cout << GetTime() << "reslease ok" << endl;
Sleep(2000);
}
return 0;
}
//进程2
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <windows.h>
using namespace std;
class MyClass
{
public:
MyClass(string lockName)
{
name = lockName;
};
~MyClass()
{
CloseHandle(hMutex);
hMutex = NULL;
};
void Lock()
{
hMutex = CreateMutex(NULL, false, name.c_str());
while (WaitForSingleObject(hMutex, INFINITE) != WAIT_OBJECT_0)
{
Sleep(1);
};
}
void UnLock()
{
hMutex = CreateMutex(NULL, false, name.c_str());
ReleaseMutex(hMutex);
}
private:
HANDLE hMutex;
string name;
};
static MyClass* myLock = new MyClass("mypmutex");
string GetTime()
{
SYSTEMTIME sys;
GetLocalTime(&sys);
char temp[256];
char name[256];
sprintf(temp, "%4d-%02d-%02d %02d:%02d:%02d-",
sys.wYear, sys.wMonth,
sys.wDay, sys.wHour,
sys.wMinute, sys.wSecond);
std::string inStr;
inStr += temp;
return inStr;
}
int main()
{
for (int i = 0;i < 10; i++)
{
myLock->Lock();
cout << GetTime() << "begin sleep" << endl;
Sleep(5000);
cout << GetTime() << "process 111111111111111111111111111" << endl;
myLock->UnLock();
cout << GetTime() << "reslease ok" << endl;
Sleep(2000);
}
return 0;
}
参考: 1.https://blog.csdn.net/cainiaoxunchong/article/details/19089991 2.https://blog.csdn.net/u013659062/article/details/101086972 3.https://blog.csdn.net/icebergliu1234/article/details/104665904
|