《ASCE1885的源码分析》の跨平台互斥对象Mutex封装类
1)首先定义互斥对象的接口IMutex(所在文件是IMutex.h)
class IMutex //抽象接口
{
public:
virtual ~IMutex() {}
virtual void Lock() const = 0;
virtual void Unlock() const = 0;
};
2)接着是实现IMutex接口的实现类Mutex
头文件是Mutex.h:
#ifndef _WIN32
#include <pthread.h>
#else
#include <windows.h>
#endif
#include "IMutex.h"
class Mutex : public IMutex
{
public:
Mutex();
~Mutex();
virtual void Lock() const;
virtual void Unlock() const;
private:
#ifdef _WIN32
HANDLE m_mutex; //互斥对象的句柄
#else
mutable pthread_mutex_t m_mutex;
#endif
};
实现文件Mutex.cpp:
#include "Mutex.h"
Mutex::Mutex()
{
#ifdef _WIN32
m_mutex = ::CreateMutex(NULL, FALSE, NULL); //调用Win32 API创建互斥对象
#else
pthread_mutex_init(&m_mutex, NULL);
#endif
}
Mutex::~Mutex()
{
#ifdef _WIN32
::CloseHandle(m_mutex); //在析构函数中关闭句柄
#else
pthread_mutex_destroy(&m_mutex);
#endif
}
void Mutex::Lock() const
{
#ifdef _WIN32
DWORD d = WaitForSingleObject(m_mutex, INFINITE); //调用等待函数来获取互斥对象
//(只有在拥有该互斥的线程调用ReleaseMutex释放掉该互斥对象,
//等待函数才返回,即本线程才获得互斥对象)
/// /todo check 'd' for result
#else
pthread_mutex_lock(&m_mutex);
#endif
}
void Mutex::Unlock() const
{
#ifdef _WIN32
::ReleaseMutex(m_mutex); //释放互斥对象,以便其他线程获取
#else
pthread_mutex_unlock(&m_mutex);
#endif
}
3)最后我们不直接调用Mutex类,而是对它再进行一次封装,即增加类Lock来使用Mutex:
头文件Lock.h:
class IMutex;
class Lock
{
public:
Lock(const IMutex&);
~Lock();
private:
const IMutex& m_mutex;
};
实现文件Lock.cpp:
#include "IMutex.h"
#include "Lock.h"
Lock::Lock(const IMutex& m) : m_mutex(m)
{
m_mutex.Lock();
}
Lock::~Lock()
{
m_mutex.Unlock();
}
posted on 2010-09-06 22:40 android开发实例 阅读(289) 评论(0) 编辑 收藏 举报