创建互斥体
HANDLE WINAPI CreateMutex( _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes, //安全属性 _In_ BOOL bInitialOwner,//创建者是否拥有
所有权 真为拥有 _In_opt_ LPCTSTR lpName//名称);
ReleaseMutex(hMutex); 释放互斥体
所有权,设置没有任何线程拥有
WaitForSingleObject(hMutex,INFINITE);//等待释放Mutex;INFINITE无限等待,只有没有线程拥有HMutex才会返回
以下是c++ 代码演示
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
HANDLE g_hMutex;
DWORD ticket = 100;
DWORD WINAPI Fun1(_In_ LPVOID lpParameter);
DWORD WINAPI Fun2(_In_ LPVOID lpParameter);
int main()
{
g_hMutex = CreateMutex(NULL, false, NULL);//创建互斥体
HANDLE hThread1 = CreateThread(NULL, 0, Fun1, 0, 0, 0);
HANDLE hThread2 = CreateThread(NULL, 0, Fun2, 0, 0, 0);
getchar();
CloseHandle(g_hMutex);
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}
DWORD WINAPI Fun1(_In_ LPVOID lpParameter)
{
while (true)
{
WaitForSingleObject(g_hMutex,INFINITE);
if (ticket > 0)
cout << "线程1 Ticket:" << ticket-- << endl;
else
break;
ReleaseMutex(g_hMutex);
}
return 0;
}
DWORD WINAPI Fun2(_In_ LPVOID lpParameter)
{
while (true)
{
WaitForSingleObject(g_hMutex, INFINITE);
if (ticket > 0)
cout << "线程2 Ticket:" << ticket-- << endl;
else
break;
ReleaseMutex(g_hMutex);
}
return 0;
}