1.概述
锁机制是多线程并发情景下一种控制共享资源访问的同步机制。Mutex与FastMutex相似,它们都可以借助ScopedLock模板类来自动地对互斥量进行上锁和解锁。不同的是,Mutex是递归的,这意味着同一个互斥量允许被同一个线程锁定多次;FastMutex是非递归的,这意味着如果同一个线程尝试再次锁定一个已经被锁定的互斥量,将会出现死锁的现象。
2.类图
2.1)Mutex私有继承于MutexImpl,类内包含模板参数为Mutex的ScopedLock类声明。
2.2)FastMutex私有继承于FastMutexImpl,类内包含模板参数为FastMutex的ScopedLock类声明,FastMutexImpl公有继承于MutexImpl。
2.3)MutexImpl类封装了linux互斥锁相关的系统调用。
2.4)ScopedLock模板类的析构和构造函数对传入“锁对象”进行上锁和解锁操作。
3.接口解析
template <class M>
class ScopedLock
/// A class that simplifies thread synchronization
/// with a mutex.
/// The constructor accepts a Mutex (and optionally
/// a timeout value in milliseconds) and locks it.
/// The destructor unlocks the mutex.
{
public:
explicit ScopedLock(M& mutex): _mutex(mutex)
{
_mutex.lock();
}
ScopedLock(M& mutex, long milliseconds): _mutex(mutex)
{
_mutex.lock(milliseconds);
}
~ScopedLock()
{
try
{
_mutex.unlock();
}
catch (...)
{
poco_unexpected();
}
}
private:
M& _mutex;
ScopedLock();
ScopedLock(const ScopedLock&);
ScopedLock& operator = (const ScopedLock&);
};
3.1Mutex
3.1.1构造函数
Mutex::Mutex()
{
}
MutexImpl::MutexImpl()
{
#if defined(POCO_VXWORKS)
/// ... ...
#endif
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
#if defined(PTHREAD_MUTEX_RECURSIVE_NP)
/// ... ...
#elif !defined(POCO_VXWORKS)
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
#endif
if (pthread_mutex_init(&_mutex, &attr))
{
pthread_mutexattr_destroy(&attr);
throw SystemException(