大家都知道多线程编程学习中有一个很重要的东西——引用计数,一个线程的生或死或运行状态都跟这个计数有关,他同样是在适当的时候加加减减的。这篇文章的目的就是模拟下简单的引用计数,原因是因为项目中GateServer莫名宕机,而且运维没有给过来宕机详细信息中的偏移地址,所以纵然我们又cod文件也没法查找问题所在,所以就想出了这样一个笨办法,在每个函数都加上调用计数,这样超过一定次数的我们就认为它可能是死递归,从而方便确定问题。下面给出一个简单的引用计数类的代码。(没有写成模板,因为模板的理解成本有点高,所以在项目中不太使用)
[cpp]
/************************************************************************
FileName:AutoRefCount.h
Author :eliteYang
URL :http://www.cppfans.org
Desc :引用计数
************************************************************************/
#ifndef __AUTO_REF_COUNT_H__
#define __AUTO_REF_COUNT_H__
#pragma once
class RefCount
{
public:
RefCount() : _refCount( 0 ){}
~RefCount(){}
void AddRefCount(){ ++_refCount; }
void DecRefCount()
{
–_refCount;
if ( _refCount < 0 )
{ _refCount = 0; }
}
int GetRefCount(){ return _refCount; }
private:
int _refCount;
};
class PtrRefCount
{
public:
PtrRefCount( RefCount* pRef, int nValue = 100 ) : pRefCount( pRef ), nCount( nValue )
{
if ( NULL != pRefCount )
{
pRefCount->AddRefCount();
}
}
~PtrRefCount()
{
if ( NULL != pRefCount )
{
pRefCount->DecRefCount();
}
}
bool CheckCount( char* szFunction )
{
if ( NULL == pRefCount )
{ return false; }
if ( pRefCount->GetRefCount() > nCount )
{
std::cout << "Function " << szFunction << " call error, maybe dead recursion, please check the code" << std::endl;
return false;
}
return true;
}
private:
RefCount* pRefCount;
const int nCount;
};
#endif
[/cpp]
下载我们写一个例子来测试下,我们故意写一个死递归来检验代码。如下:
[cpp]
#include "AutoRefCount.h"
#include <iostream>
#define __FUNCTION_CALL_COUNT__ RefCount _ref; \
PtrRefCount ptrRef( &_ref ); \
ptrRef.CheckCount( __FUNCTION__ );
void function()
{
__FUNCTION_CALL_COUNT__;
function();
}
int _tmain(int argc, _TCHAR* argv[])
{
function();
return 0;
}
[/cpp]
结果我们发现打出了该函数可能死递归的Log,这样我们就方便查找问题了。希望对你有用!