开发高性能的并发应用时遇到的问题常可以归结到读写锁模式。利用boost thread库,可以很简单地实现一个读写锁。不过boost thread库本来就包含读写锁了。boost实现的是传统读写锁的refinement。boost的锁分为三级:shared_lock,这个可以看作是传统的读锁;upgrade_lock;unique_lock,这个是传统的写锁。什么是upgrade_lock,它的最大特点就是与shared_lcok不互斥,与别的upgrade_lock和unique_lock互斥。
也就是说线程A获得mutex的upgrade_lock后,线程B、C等还可以获得mutex的share_mutex。反之亦然。另外,upgrade_lock可以升级为upgrade_to_unique_lock。据boost文档说也可以downgrade成shared_lock,但我没找到相关的锁类型,不过自己实现也不难,因为UpgradeLockable Concept需要提供以下几个函数:
void unlock_upgrade_and_lock(); // 从upgrade升级到unique
void unlock_and_lock_upgrade(); // 从unique降级到ungrade
void unlock_upgrade_and_lock_shared(); // upgrade降级到shared
boost库提供的读写锁函数如下:
#include <boost/thread.hpp>
#include <boost/function.hpp>
typedef boost::shared_lock<boost::shared_mutex> boost_share_lock;
typedef boost::unique_lock<boost::shared_mutex> boost_unique_lock;
//共享读控制锁
boost::shared_mutex m_mutexResource;
boost_share_lock lockReader(m_mutexResource);
//...共享读代码
//同步写控制锁
boost_unique_lock lockWriter(m_mutexResource);
//...同步写代码
boost读写锁使用实例代码如下:
注:运行环境:VS2005,boost 1.46.1
#include <Windows.h>
#include <process.h>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread.hpp>
using namespace std;
typedef boost::shared_mutex rwmutex;
typedef boost::shared_lock<rwmutex> readLock;
typedef boost::unique_lock<rwmutex> writeLock;
rwmutex _rwmutex;
int cc_count = 0;
void __cdecl readOnly(LPVOID lpParameter)
{
readLock rdLock(_rwmutex);
//do something...
}
void __cdecl writeOnly(LPVOID lpParameter)
{
writeLock wlock(_rwmutex);
//do something...
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i=0;i<15;i++)
{
_beginthread(readOnly, 0, 0);
_beginthread(writeOnly, 0, 0);
}
Sleep(INFINITE);
return 0;
}