简介
Windows互斥对象机制。 只有拥有互斥对象的线程才有访问公共资源的权限,因为互斥对象只有一个,所以能保证公共资源不会同时被多个线程访问,在线程同步与保证程序单体运行上都有相当大的用处。
代码样例
////////////////////////////////
//
// FileName : MutexDemo.cpp
// Creator : PeterZheng
// Date : 2018/10/23 21:27
// Comment : The usage of "CreateMutex"
//
////////////////////////////////
#pragma once
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
DWORD WINAPI Func1(LPVOID lpParam);
DWORD WINAPI Func2(LPVOID lpParam);
HANDLE hMutex = NULL;
int g_num = 0;
DWORD WINAPI Func1(LPVOID lpParam)
{
while (g_num < 100)
{
WaitForSingleObject(hMutex, INFINITE);
cout << "Count: " << g_num << endl;
g_num++;
Sleep(10);
ReleaseMutex(hMutex); // 释放互斥体
}
return 0;
}
DWORD WINAPI Func2(LPVOID lpParam)
{
while (g_num < 100)
{
WaitForSingleObject(hMutex, INFINITE);
cout << "Count: " << g_num << endl;
g_num++;
Sleep(10);
ReleaseMutex(hMutex);
}
return 0;
}
int main(void)
{
hMutex = CreateMutex(NULL, FALSE, "Mutex"); // 创建互斥体
HANDLE hThread[2] = { 0 };
hThread[0] = CreateThread(NULL, 0, Func1, NULL, 0, NULL); // 创建线程1
hThread[1] = CreateThread(NULL, 0, Func2, NULL, 0, NULL); // 创建线程2
WaitForMultipleObjects(2, hThread, TRUE, INFINITE); // 等待线程执行结束
system("pause");
return 0;
}