简单的模拟多线程引用计数原理

1649 篇文章 11 订阅
1010 篇文章 11 订阅

大家都知道多线程编程学习中有一个很重要的东西——引用计数,一个线程的生或死或运行状态都跟这个计数有关,他同样是在适当的时候加加减减的。这篇文章的目的就是模拟下简单的引用计数,原因是因为项目中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,这样我们就方便查找问题了。希望对你有用!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值