c++ 对关键段CRITICAL_SECTION的封装

 

/仅头文件,使用引用计数为其他引用对象进行计数
#include "stdafx.h"

/*对关键段(临界区的封装),方便直接使用*/
/*关键段仅在线程内使用,不像内核对象,即可在进程内使用,也可在线程内使用*/
#pragma  once
/*封装关键段的类,使用全局静态类对象,这样,才能在入口函数之前自动初始化,在退出入口函数之后自动析构*/
class CWarpCriticalSection{
public:
	inline CWarpCriticalSection(){
		this->pCriSec= new CRITICAL_SECTION;
		InitializeCriticalSection(pCriSec);
		this->prefcount=new LONG(1);
	}
	inline virtual ~CWarpCriticalSection(){
		this->Release();//没办法,只能失败拋异常了
		//或许这里应当强制释放,否则有可能使整个进程或者某些线程挂起
	}
	inline  CWarpCriticalSection(CWarpCriticalSection& m){
		InterlockedIncrement(m.prefcount);//如果 指针为无效,就会抛异常
		this->pCriSec=m.pCriSec;
		this->prefcount=m.prefcount;
	}
	inline	CWarpCriticalSection& operator =(CWarpCriticalSection& m){
		if(m.pCriSec){
			this->Release();
			InterlockedIncrement(m.prefcount);//如果 指针为无效,就会抛异常
			this->pCriSec=m.pCriSec;
			this->prefcount=m.prefcount;
		}
		return *this;
	}

	inline void Lock(){
		EnterCriticalSection(this->pCriSec);
	}

	inline void UnLock(){
		LeaveCriticalSection(this->pCriSec);
	}
private:
	inline void Release(){
		if(0>=InterlockedDecrement(prefcount/*如果对象无效呢*/)){
			DeleteCriticalSection(pCriSec);/*这里也是*/
			delete this->pCriSec;			
			delete this->prefcount;
			this->pCriSec=NULL;
			this->prefcount=NULL;
		}
	}
private:
	LPCRITICAL_SECTION    pCriSec;
	LONG* prefcount;//引用计数
}; 
typedef CWarpCriticalSection *PCWarpCriticalSection,*LPCWarpCriticalSection;


/*全局对象,有副作用,会影响不相关的代码,如果仅使用小片代码,则可以使用,不能用于 多个管理例程*/
static CWarpCriticalSection  __critical_section;

/*关键段 锁住*/
#ifndef  __LOCK
#define  __LOCK     __critical_section.Lock() ;
#endif 

/*关键段 解锁*/
#ifndef __UNLOCK
#define __UNLOCK  __critical_section.UnLock();
#endif
 



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值