多线程临界区

#include <stdio.h>
#include <Windows.h>
#include <process.h>
BOOL g_bContinue = TRUE;
int g_nCount1 = 0;
int g_nCount2 = 0;
CRITICAL_SECTION g_cs;//对存在同步问题的代码段使用临界区对象
UINT _stdcall ThreadFunc(LPVOID)
{
	while (g_bContinue)
	{
		::EnterCriticalSection(&g_cs);
		g_nCount1++;
		g_nCount2++;
		::LeaveCriticalSection(&g_cs);
	}
	return 0;
}


int main(void)
{
	UINT uId;
	HANDLE h[2];
	//初始化临界区对象
	::InitializeCriticalSection(&g_cs);
	h[0] = (HANDLE)::_beginthreadex(NULL, 0, ThreadFunc, NULL, 0, &uId);
	h[1] = (HANDLE)::_beginthreadex(NULL, 0, ThreadFunc, NULL, 0, &uId);
	//等待1秒后通知两个计数线程结束,关闭句柄
	Sleep(1000);
	g_bContinue = FALSE;
	::WaitForMultipleObjects(2, h, TRUE, INFINITE);
	if (h[0])
	::CloseHandle(h[0]);
	if (h[1])
	::CloseHandle(h[1]);
	//删除临界区对象
	::DeleteCriticalSection(&g_cs);
	printf_s("g_nCount1=%d\n", g_nCount1);
	printf_s("g_nCount2=%d\n", g_nCount2);
	return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值