1. 程式人生 > >C++簡單封裝互斥量

C++簡單封裝互斥量

在編寫多執行緒程式中,經常需要遇到多執行緒同步操作,例如操作sqlite3資料庫,寫一個日誌檔案,操作一個連結串列等,只能同時一個執行緒操作,因此需要經常用到互斥鎖。

筆者為了方便使用,採用C++簡單封裝Linux互斥鎖,根據建構函式的引數,可以建立遞迴互斥鎖和非遞迴互斥鎖。


程式碼如下:

CMutex.h

/*************************************************************************
    > File Name: CMutex.h
    > Author: KentZhang
    > Mail: 
[email protected]
> Created Time: Wed 02 Sep 2015 01:49:15 PM CST ************************************************************************/ #ifndef __CMUTEX_H__ #define __CMUTEX_H__ #include <pthread.h> #include <sys/types.h> class CMutex { public: CMutex(bool IsRecursive=false);//預設建立非遞迴互斥鎖 ~CMutex(); bool Lock(); bool UnLock(); bool TryLock(); private: pthread_mutex_t *m_pMutex; }; #endif

CMutex.cpp

/*************************************************************************
  > File Name: CMutex.cpp
  > Author: KentZhang
  > Mail: [email protected]
  > Created Time: Wed 02 Sep 2015 01:46:36 PM CST
 ************************************************************************/

//封裝互斥鎖
#include "CMutex.h"
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DEBUG_ERROR(format,...)  do{ printf(""format", FileName:%s, FuncName:%s, LineNum:%d\n",\
				     ##__VA_ARGS__, __FILE__, __func__, __LINE__);}while(0)

CMutex::CMutex(bool IsRecursive)
{
	m_pMutex = new pthread_mutex_t;
	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	int nResult = 0;
	do{
		if (IsRecursive)
		{  
			//設定屬性為可遞迴
			nResult = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
			nResult = 20;
			if ( 0 != nResult )
			{
				DEBUG_ERROR("pthread_mutexattr_settype() failed:%s", strerror(nResult));
				break;
			}
		}
		else
		{   
			//設定屬性為不可遞迴
			nResult = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
			if ( 0 != nResult )
			{
				DEBUG_ERROR("pthread_mutexattr_settype() failed:%s", strerror(nResult));
				break;
			}	
		}

		nResult = pthread_mutex_init(m_pMutex, &attr);
		if( 0 != nResult )
		{
			DEBUG_ERROR("pthread_mutexattr_settype() failed:%s", strerror(nResult));
			break;
		}
	}while(0);
	
}

CMutex::~CMutex()
{
	int nResult = pthread_mutex_destroy(m_pMutex);
	if( nResult != 0 )
	{
		DEBUG_ERROR("CMutex ~CMutex() pthread_mutex_destroy() failed:%s", strerror(nResult));
	}
	if ( m_pMutex != NULL )
		delete m_pMutex;
}

bool CMutex::Lock()
{
	int nResult = pthread_mutex_lock(m_pMutex);
	if( nResult < 0 )
	{
		DEBUG_ERROR("CMutex lock() pthread_mutex_lock() failed:%s", strerror(nResult));
		return false;
	}
	return true;
}

bool CMutex::UnLock()
{
	int nResult = pthread_mutex_unlock(m_pMutex);
	if ( nResult < 0 )
	{
		DEBUG_ERROR("CMutex unlock() pthread_mutex_unlock() failed:%s", strerror(nResult));
		return false;
	}
	return true;
}

bool CMutex::TryLock()
{
	int nResult = pthread_mutex_trylock(m_pMutex);
	if ( nResult !=  0 )
	{
		DEBUG_ERROR("CMutex trylock() pthread_mutex_trylock() failed:%s", strerror(nResult));
		return false;
	}
	return true;
}


由於筆者的水平有限,出錯在所難免,懇請讀者拍磚指正,謝謝閱讀