互斥对象 例子 (多线程全局变量问题)

前面,关于多线程全局变量问题,,已经介绍过,临界区事件对象,,,那么还有一样方式,就是互斥对象..

就是书上P129页的例子..

#include <stdio.h>
#include <windows.h>
#include <process.h>
BOOL g_bContinue = TRUE; //用于通知线程退出的标志变量
int g_nCount1 = 0;
int g_nCount2 = 0;
UINT __stdcall ThreadFunc1(LPVOID);
UINT __stdcall ThreadFunc2(LPVOID);
HANDLE g_hMutex; //用于同步控制的全局互斥对象句柄
int main(int argc, char* argv[])
{
	UINT uId;
	HANDLE h[2];
	//创建一个主线程初始不拥有的匿名互斥对象 
	g_hMutex=CreateMutex(NULL,FALSE,NULL);
	h[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc2, NULL, 0, &uId);
	h[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc1, NULL, 0, &uId);
	// 等待500毫秒后通知两个计数线程结束,关闭句柄
	Sleep(500);
	g_bContinue = FALSE; //通知两个线程退出
	WaitForMultipleObjects(2, h, TRUE, INFINITE); //等待两个线程都退出
	CloseHandle(h[0]);  //关闭线程1的句柄
	CloseHandle(h[1]);  //关闭线程2的句柄
	CloseHandle(g_hMutex);//关闭互斥对象句柄
	return 0;
}
UINT __stdcall ThreadFunc1(LPVOID)
{
	while(g_bContinue)
	{ 
		WaitForSingleObject(g_hMutex, INFINITE); //等待拥有互斥对象
		g_nCount1++;
		printf(" -> 装入一颗炸弹\n"); 
		ReleaseMutex(g_hMutex); //释放拥有的互斥对象
	}
	return 0;
}
UINT __stdcall ThreadFunc2(LPVOID)
{
	while(g_bContinue)
	{ 
		WaitForSingleObject(g_hMutex, INFINITE); //等待拥有互斥对象
		if (g_nCount1 != 0)
		{
			printf("** 同时引爆 %d 颗炸弹\n\n", g_nCount1);
			g_nCount1 = 0;
		}
		ReleaseMutex(g_hMutex); //释放拥有的互斥对象
	}
	return 0;
}

 

评论列表