作者:黃山松,發表於cnblogs:http://www.cnblogs.com/tomview/
對於一個 win 的程序員,要把在 win 下的程序移植到 linux 下,需要把一些平台相關的功能代碼封裝一下,這樣在使用這些功能的時候,可以簡單調用封裝好的代碼,方便在不同平台下使用。本文是一個非常簡單的互斥類,通過使用這個互斥類,源代碼在 linux 下和 win 下保持一致。
在 win 下,互斥的代碼是這幾個函數:
InitializeCriticalSection
EnterCriticalSection
LeaveCriticalSection
DeleteCriticalSection
TryEnterCriticalSection
在 Linux 下,可以用對應的下面函數實現:
pthread_mutex_init
pthread_mutex_destroy
pthread_mutex_lock
pthread_mutex_unlock
封裝類 auto_entercs 之後,不管在 win 還是 linux 下都使用相同的 win 下的函數就可以了,如下:
用法:
#include "auto_entercs.h"
CRITICAL_SECTION m_cs;
InitializeCriticalSection(&m_cs);
DeleteCriticalSection(&m_cs);
在需要互斥的代碼區域開頭聲明類 auto_entercs 的局部變量,類的構造函數中自動調用 EnterCriticalSection 獲取控制權,在出了變量作用域的時候,類的析構函數自動調用 LeaveCriticalSection 釋放控制權。
{
//作用域的開始聲明局部變量
auto_entercs ace(&m_cs);
//互斥區域代碼。。。
//離開作用域的時候自動釋放控制權
}
auto_entercs.h 的代碼如下:
#ifndef _X_HSS_CRITICAL_SECTION_HSS__
#define _X_HSS_CRITICAL_SECTION_HSS__
/**************************************************************************************************\
用於 win32 和 linux 下的通用的互斥類,如下的使用代碼在 win 下和 linux 下使用同樣的代碼使用互斥
用法:
(0) 包含
#include "auto_entercs.h"
(1) 定義
CRITICAL_SECTION m_cs;
(2) 初始化
InitializeCriticalSection(&m_cs);
(3) 進入和離開互斥
{
auto_entercs ace(&m_cs);
....互斥區域
}
(4) 刪除
DeleteCriticalSection(&m_cs);
作者: 黃山松,http://www.cnblogs.com/tomview/
\**************************************************************************************************/
#ifdef WIN32
#include <windows.h>
#else
#include <pthread.h>
#define CRITICAL_SECTION pthread_mutex_t
#define InitializeCriticalSection(p) \
{ \
pthread_mutexattr_t attr; \
pthread_mutexattr_init(&attr); \
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); \
pthread_mutex_init((p), &attr); \
}
#define DeleteCriticalSection(p) pthread_mutex_destroy(p)
#define EnterCriticalSection(p) pthread_mutex_lock(p)
#define LeaveCriticalSection(p) pthread_mutex_unlock(p)
#endif
//auto_entercs 需要在互斥代碼區域內聲明局部變量,當代碼執行出區域的時候,析構函數自動調用LeaveCriticalSection
class auto_entercs
{
public:
auto_entercs(CRITICAL_SECTION* pcs)
{
m_pcs = pcs;
if (m_pcs)
{
EnterCriticalSection(m_pcs);
}
}
~auto_entercs()
{
if (m_pcs)
{
LeaveCriticalSection(m_pcs);
}
}
CRITICAL_SECTION* m_pcs;
};
#endif