//main.cpp
#include <windows.h>
#include <iostream>
DWORD WINAPI Fun_1(LPVOID p);
DWORD WINAPI Fun_2(LPVOID p);
HANDLE h_mutex;
unsigned int counter = 0;
int main()
{
h_mutex = CreateMutex(nullptr, false, nullptr);
HANDLE h1 = CreateThread(nullptr, 0, Fun_1, nullptr, 0, nullptr);
std::cout << "Thread 1 started...\n";
HANDLE h2 = CreateThread(nullptr, 0, Fun_2, nullptr, 0, nullptr);
std::cout << "Thread 2 started...\n";
CloseHandle(h1);
CloseHandle(h2);
//
//CloseHandle(h_mutex);
system("pause");
return 0;
}
DWORD WINAPI Fun_1(LPVOID p)
{
while (true)
{
WaitForSingleObject(h_mutex, INFINITE);
if (counter < 1000)
{
++counter;
std::cout << "Thread 1 counting " << counter << "...\n";
ReleaseMutex(h_mutex);
}
else
{
ReleaseMutex(h_mutex);
break;
}
}
return 0;
}
DWORD WINAPI Fun_2(LPVOID p)
{
while (true)
{
WaitForSingleObject(h_mutex, INFINITE);
if (counter < 1000)
{
++counter;
std::cout << "Thread 2 counting " << counter << "...\n";
ReleaseMutex(h_mutex);
}
else
{
ReleaseMutex(h_mutex);
break;
}
}
return 0;
}
1、CreateMutex
HANDLE h_mutex;
h_mutex = CreateMutex(nullptr, false, nullptr);
2、CloseHandle
3、 WaitForSingleObject(h_mutex, INFINITE);
4、ReleaseMutex(h_mutex);
互斥量
采用互斥对象机制。 只有拥有互斥对象的线程才有访问公共资源的权限,因为互斥对象只有一个,所以能保证公共资源不会同时被多个线程访问。互斥不仅能实现同一应用程序的公共资源安全共享,还能实现不同应用程序的公共资源安全共享