/仅头文件,使用引用计数为其他引用对象进行计数
#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