1. 程式人生 > >簡單的模擬多執行緒引用計數原理

簡單的模擬多執行緒引用計數原理

大家都知道多執行緒程式設計學習中有一個很重要的東西——引用計數,一個執行緒的生或死或執行狀態都跟這個計數有關,他同樣是在適當的時候加加減減的。這篇文章的目的就是模擬下簡單的引用計數,原因是因為專案中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,這樣我們就方便查詢問題了。希望對你有用!