V : jbossjf
如果某个文件不允许被多个进程用时使用,这时候也可以采用进程间互斥。当一个进程创建一个进程后创建一个锁,第二个进程使用OpenMutex获取第一个进程创建的互斥锁的句柄。
代码:
#include<Windows.h>
#include<iostream>
using namespace std;
//互斥锁
HANDLE hMutex1;
int flag;
DWORD WINAPI MyThread(LPVOID lpParamter)
{
while (1)
{
WaitForSingleObject(hMutex1,INFINITE);
flag=!flag;
cout << "MyThread2 Runing"<<"进程1" <<" "<<flag<< endl;
Sleep(500);
//此时锁1被锁,无法在下面解锁2
ReleaseMutex(hMutex1);
}
}
int main()
{
//创建一个锁
hMutex1 =CreateMutex(NULL,false,LPCWSTR("hMutex1"));
HANDLE hThread1 = CreateThread(NULL, 0, MyThread, NULL, 0, NULL);
CloseHandle(hThread1);
while(1);
return 0;
}
第二个进程:
代码:
#include<Windows.h>
#include<iostream>
using namespace std;
//互斥锁
HANDLE hMutex1;
int flag;
//无参数
DWORD WINAPI MyThread(LPVOID lpParamter)
{
while (1)
{
WaitForSingleObject(hMutex1,INFINITE);
flag=!flag;
cout << "MyThread2 Runing"<<"进程2" <<" "<<flag<< endl;
Sleep(5000);
ReleaseMutex(hMutex1);
}
}
int main()
{
//打开
hMutex1 = OpenMutex(MUTEX_ALL_ACCESS,false,LPCWSTR("hMutex1"));
if(hMutex1!=NULL)
cout<<"锁打开成功"<<endl;
HANDLE hThread1 = CreateThread(NULL, 0, MyThread, NULL, 0, NULL);
CloseHandle(hThread1);
while(1);
return 0;
}