在PureMVC框架(c++版本)中看到了对于map对象的保护锁,利用构造、析构函数实现便捷的lock和unlock操作。
下面的是代码中搜到的锁对象,发现在model、view、controller三个类中分别定义了同名的一个锁(非同一把锁)。

例如Controller模块中的成员变量:
mutable FastMutex _synchronous_access;
这个锁是用来同步CommandMap _command_map的,这个map涉及插入、删除操作,在多线程中需要保护。具体怎么使用这个FastMutex类型的锁呢?先来看看插入、删除操作中的用法:
void Controller::registerCommand(std::string const& notification_name, ICommand* command)
{
PureMVC::FastMutex::ScopedLock lock(_synchronous_access); //加锁保护
if (_command_map.find(notification_name) == _command_map.end() )
{
if (_view == NULL)
throwException<std::runtime_error>("Cannot register command [%s]. View is null.", notification_name.c_str());
IObserver* observer = createObserver(&Controller::executeCommand, this);
puremvc_observer_instance_map.insert(observer);
_view->registerObserver(notification_name, observer);
}
command->initializeNotifier(_multiton_key);
_command_map[notification_name] = command;
}
先来看看定义:
namespace PureMVC
{
template<typename _Lockable> //这是一个模板函数
class UniqueLock
{
private:
_Lockable& _lockable;
private:
UniqueLock(UniqueLock const&);
UniqueLock& operator=(UniqueLock const&);
public:
explicit UniqueLock(_Lockable& lockable)
: _lockable(lockable)
{
_lockable.lock(); //构造函数执行lock操作
}
~UniqueLock(void)
{
_lockable.unlock(); //利用析构函数完成unlock操作
}
};
class PUREMVC_API Mutex //1.定义了Metux类型的锁
{
private:
void* _mutex;
public:
typedef UniqueLock<Mutex> ScopedLock; //声明了一个类型别名
public:
explicit Mutex(void);
public:
void lock(void);
bool tryLock(void);
void unlock(void);
~Mutex(void);
};
class PUREMVC_API FastMutex //2.定义了FastMutex类型的锁
{
private:
void* _mutex;
public:
typedef UniqueLock<FastMutex> ScopedLock;
public:
explicit FastMutex(void);
public:
void lock(void);
bool tryLock(void);
void unlock(void);
~FastMutex(void);
};
}
其中FastMutex的成员函数lock、unlock定义如下:
void FastMutex::lock(void)
{
puremvc_fast_mutex_t* mutex = (puremvc_fast_mutex_t*)_mutex;
#if defined(_WIN32) || defined(_WIN64)
EnterCriticalSection(mutex); //windows下进入临界区
#else
register int rc;
if ((rc = ::pthread_mutex_lock(mutex))) //linux下加锁
{
std::cerr << strerror(rc) << std::endl;
throw std::runtime_error("Cannot lock mutex!");
}
#endif
}
void FastMutex::unlock(void)
{
puremvc_fast_mutex_t* mutex = (puremvc_fast_mutex_t*)_mutex;
#if defined(_WIN32) || defined(_WIN64)
LeaveCriticalSection(mutex); //windows下离开临界区
#else
register int rc;
if ((rc = ::pthread_mutex_unlock(mutex))) //linux下解锁
{
std::cerr << strerror(rc) << std::endl;
throw std::runtime_error("Cannot unlock mutex!");
}
#endif
}
再来分析下这个语句:
PureMVC::FastMutex::ScopedLock lock(_synchronous_access);
解析:
ScopedLock是FastMutex的一个成员变量,所以上述语句等价于:
PureMVC::FastMutex::UniqueLock<FastMutex> lock(_synchronous_access);
这里相当于定义了一个UniqueLock的类对象,并给该类的构造函数传入了一个
FastMutex类型的参数,UniqueLock类的构造函数执行的就是FastMutex的lock
操作,析构函数执行的是FastMutex的unlock操作。
网友评论