WIN 程序员的 Linux 互斥类

时间:2023-03-08 16:39:19

作者:黄山松,发表于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