linux c++ 统计日志的线程安全类

class CLLog
{
public:
	static CLLog* GetInstance();

	static CLStatus WriteLogMsg(const char *pstrMsg, long lErrorCode);

	CLStatus WriteLog(const char *pstrMsg, long lErrorCode);

private:
	CLLog(const CLLog&);
	CLLog& operator=(const CLLog&);

	static pthread_mutex_t *InitializeMutex();

private:
	CLLog();
	~CLLog();

	int m_Fd;
	pthread_mutex_t *m_pMutexForFile;

	static CLLog * volatile  m_pLog;
	static pthread_mutex_t *m_pMutex;
};
CLLog* volatile CLLog::m_pLog = 0;

pthread_mutex_t *CLLog::m_pMutex = CLLog::InitializeMutex();

注意:m_pMutexForFile是为每个文件互斥的,所以是成员变量

     而m_pMutex是用于对保证了多线程环境下只会创建一个对象使用的。所以是静态成员变量。

m_pLog之所以是volatile的,是因为在多线程环境下防止其他线程已经构造了这个静态对象。

CLLog* CLLog::GetInstance()
{
	if(m_pMutex == 0)
		return 0;
		
	int r = pthread_mutex_lock(m_pMutex);
	if(r != 0)
		return 0;
		
	if(m_pLog == 0)
	{
		m_pLog = new CLLog;
	}

	r = pthread_mutex_unlock(m_pMutex);
	if(r != 0)
		return 0;

	return m_pLog;
}

但每次读都需要加锁、解锁,效率不高
能否让后续的读操作,不再加锁

双重检测机制:

CLLog* CLLog::GetInstance()
{
	if(m_pLog == 0)
	{
		if(m_pMutex == 0)
			return 0;
		
		int r = pthread_mutex_lock(m_pMutex);
		if(r != 0)
			return 0;
		
		if(m_pLog == 0)
		{
			m_pLog = new CLLog;
		}

		r = pthread_mutex_unlock(m_pMutex);
		if(r != 0)
			return 0;
	}

	return m_pLog;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值