Win32线程同步 - 互斥器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/brunomarss/article/details/82984409

/*

*        说明:Mutex(互斥器)的使用

*        特点:1.一个时间只能有一个线程拥有mutex,这点类似critical section

*                   2.可以跨进程使用,需要创建时指定名称

*                   3.可以指定“结束等待”时间长度

*/

 

	#include <iostream>
	#include <windows.h>
	#include <stdlib.h>
	
	using namespace std;
	
	HANDLE g_hMutex = NULL;
	const int g_Number = 3;
	
	DWORD WINAPI ThreadProc1(__in LPVOID lpParameter);
	DWORD WINAPI ThreadProc2(__in LPVOID lpParameter);
	DWORD WINAPI ThreadProc3(__in LPVOID lpParameter);
	
	int main()
	{
		// 创建互斥器
		g_hMutex = CreateMutex(NULL, FALSE, NULL);	// FALSE代表当前没有线程拥有这个互斥对象
	
		HANDLE hThread[g_Number] = { 0 };
		int first = 1;
		int second = 2;
		int third = 3;
	
		// 创建工作线程
		hThread[0] = CreateThread(NULL, 0, ThreadProc1, (LPVOID)first, 0, NULL);
		hThread[1] = CreateThread(NULL, 0, ThreadProc2, (LPVOID)second, 0, NULL);
		hThread[2] = CreateThread(NULL, 0, ThreadProc3, (LPVOID)third, 0, NULL);
	
		// 线程handle引用计数减1
		CloseHandle(hThread[0]);
		CloseHandle(hThread[1]);
		CloseHandle(hThread[2]);
	
		// 主线程等待多个工作线程
		WaitForMultipleObjects(g_Number, hThread, TRUE, INFINITE);
	
		system("pause");
	
		// 关闭互斥器(核心对象)
		CloseHandle(g_hMutex);
	
		return 0;
	}
	
	DWORD WINAPI ThreadProc1(__in LPVOID lpParameter)
	{
		WaitForSingleObject(g_hMutex, INFINITE);		// 等待互斥量
		cout << (int)lpParameter << endl;
		ReleaseMutex(g_hMutex);					// 释放互斥量
		return 0;
	}
	
	DWORD WINAPI ThreadProc2(__in LPVOID lpParameter)
	{
		WaitForSingleObject(g_hMutex, INFINITE);		
		cout << (int)lpParameter << endl;        
		ReleaseMutex(g_hMutex);                 
		return 0;
	}
	
	DWORD WINAPI ThreadProc3(__in LPVOID lpParameter)
	{
		WaitForSingleObject(g_hMutex, INFINITE);		
		cout << (int)lpParameter << endl;
		ReleaseMutex(g_hMutex);					
		return 0;
	}

猜你喜欢

转载自blog.csdn.net/brunomarss/article/details/82984409