1.互斥量
採用互斥對象機制。 只有擁有互斥對象的線程纔有訪問公共資源的權限,因爲互斥對象只有一個,所以能保證公共資源不會同時被多個線程訪問。互斥不僅能實現同一應用程序的公共資源安全共享,還能實現不同應用程序的公共資源安全共享。
2.使用
HANDLE hMutex; //定義互斥對象句柄
hMutex = CreateMutex(NULL, false, "mutex"); //創建互斥對象
WaitForSingleObject(hMutex, INFINITE);
ReleaseMutex(hMutex);
3.實例
#include<windows.h>
#include<iostream>
using namespace std;
int number = 1; //定義全局變量
HANDLE hMutex; //定義互斥對象句柄
unsigned long __stdcall ThreadProc1(void* lp)
{
while (number < 100)
{
WaitForSingleObject(hMutex, INFINITE);
cout << "thread 1 :"<<number << endl;
++number;
_sleep(100);
ReleaseMutex(hMutex);
}
return 0;
}
unsigned long __stdcall ThreadProc2(void* lp)
{
while (number < 100)
{
WaitForSingleObject(hMutex, INFINITE);
cout << "thread 2 :"<<number << endl;
++number;
_sleep(100);
ReleaseMutex(hMutex);
}
return 0;
}
int main()
{
hMutex = CreateMutex(NULL, false, "mutex"); //創建互斥對象
CreateThread(NULL, 0, ThreadProc1, NULL, 0, NULL);
CreateThread(NULL, 0, ThreadProc2, NULL, 0, NULL);
Sleep(10*1000);
system("pause");
return 0;
}