Critical Section 线程同步 (C/C++ Windows Platform SDK 实现)

Mutex和Event是系统内核对象,好处是他们是跨进程的,可以用作进程间的线程同步。缺点也很明显,就是他们的速度较慢。 Critical Section则是用户对象,速度快,但是不能设置超时时间,一不小心会造成死锁。(记得操作系统课本上的哲学家饿死问题吗,幸好哲学家不搞程序,要不然非气吐血不可)。。。 一个很简单的Critical Section示例:
// Coding by nyzhl with Visual C++ 6.0

#include <windows.h>

#include <stdio.h>

//Definition of Critical Section object

CRITICAL_SECTION g_cs;

//Definition of Thread Processors

DWORD WINAPI ThreadProc1(LPVOID lpParam);

DWORD WINAPI ThreadProc2(LPVOID lpParam);



int g_count = 100;



void main()

{

	//Initialization

	InitializeCriticalSection(&g_cs);

	HANDLE thread1 = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);

	CloseHandle(thread1);

	HANDLE thread2 = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);

	CloseHandle(thread2);

	Sleep(5000);

	//Free resources of critical section

	DeleteCriticalSection(&g_cs);

}



//Implementation of Thread Processors

DWORD WINAPI ThreadProc1(LPVOID lpParam)

{

	while(true)

	{

		//*********Critical Section*************

		EnterCriticalSection(&g_cs);

		if(g_count<1) break;

		Sleep(1);

		printf("%d/n",g_count);

		g_count--;

		LeaveCriticalSection(&g_cs);

		//****************************************

	}

	return 0;

}



DWORD WINAPI ThreadProc2(LPVOID lpParam)

{

	while(true)

	{

		//************Critical Section************

		EnterCriticalSection(&g_cs);

		if(g_count<1) break;

		Sleep(1);

		printf("%d/n",g_count);

		g_count--;

		LeaveCriticalSection(&g_cs);

		//*****************************************

	}

	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值