实现boost::thread中RAII风格的共享锁

实现boost::thread中RAII风格的共享锁

实现代码:

    typedef enum { UNIQUE_LOCK, SHARED_LOCK } LockType;

template < LockType lt >
class  shared_lock;

template 
<>
class  shared_lock < UNIQUE_LOCK > private  boost::noncopyable  {
public:
    shared_lock(boost::shared_mutex
& sm): sm_(sm) sm_.lock(); }
    
~shared_lock() { sm_.unlock(); }
private:
    boost::shared_mutex
& sm_;
}
;

template 
<>
class  shared_lock < SHARED_LOCK > private  boost::noncopyable  {
public:
    shared_lock(boost::shared_mutex
& sm): sm_(sm) sm_.lock_shared(); }
    
~shared_lock() { sm_.unlock_shared(); }
private:
    boost::shared_mutex
& sm_;
}
;



调用方式:

    boost::shared_mutex session_mutex_;

// 独占锁定
shared_lock < UNIQUE_LOCK >   lock (session_mutex_);

// 共享锁定
shared_lock < SHARED_LOCK >   lock (session_mutex_);


http://www.cppblog.com/thisisbin/archive/2009/01/21/72417.html 一文 single-write/multi-read 就可以应用这种RAII风格的共享锁实

你可能感兴趣的:(实现boost::thread中RAII风格的共享锁)