std::shared_mutex
http://en.cppreference.com/w/cpp/thread/shared_mutex
GCC5.1才会支持C++17 std::shared_mutex,替代方案是boost::shared_mutex。
boost::shared_mutex官方文档:http://www.boost.org/doc/libs/1_60_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex
需要的lib:
- #pragma comment(lib, "libboost_chrono-vc140-mt-1_60.lib")
- #pragma comment(lib, "libboost_date_time-vc140-mt-1_60.lib")
- #pragma comment(lib, "libboost_system-vc140-mt-1_60.lib")
- #pragma comment(lib, "libboost_system-vc140-mt-1_60.lib")
- #pragma comment(lib, "libboost_thread-vc140-mt-1_60.lib")
boost::shared_mutex用法示例:
参考自:http://stackoverflow.com/questions/3896717/example-of-how-to-use-boost-upgradeable-mutexes
#include <boost/thread/locks.hpp> #include <boost/thread/shared_mutex.hpp> int main() { typedef boost::shared_mutex Mutex; typedef boost::shared_lock<Mutex> ReadLock; typedef boost::unique_lock<Mutex> WriteLock; Mutex mutex; { // acquire read lock ReadLock read( mutex ); // do something to read resource } { // acquire write lock WriteLock write( mutex, boost::adopt_lock_t() ); // do something to write resource } }
参考自:http://stackoverflow.com/questions/989795/example-for-boost-shared-mutex-multiple-reads-one-write
boost::shared_mutex _access; void reader() { // get shared access boost::shared_lock<boost::shared_mutex> lock(_access); // now we have shared access } void writer() { // get upgradable access boost::upgrade_lock<boost::shared_mutex> lock(_access); // get exclusive access boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock); // now we have exclusive access }
其他参考:
How to make a multiple-read/single-write lock from more basic synchronization primitives?
伟大的Boost库给我们提供了 shared_mutex 类,结合 unique_lock 与 shared_lock 的使用,可以实现读写锁。
通常读写锁需要完成以下功能:
1.当 data 被线程A读取时,其他线程仍可以进行读取却不能写入
2.当 data 被线程A写入时,其他线程既不能读取也不能写入
对应于功能1,2我们可以这样来描述:
1.当线程A获得共享锁时,其他线程仍可以获得共享锁但不能获得独占锁
2.当线程A获得独占锁时,其他线程既不能获得共享锁也不能获得独占锁
typedef boost::shared_lock<boost::shared_mutex> read_lock; typedef boost::unique_lock<boost::shared_mutex> write_lock; boost::shared_mutex read_write_mutex; int32_t data = 1; //线程A,读data { read_lock rlock(read_write_mutex); std::cout << data << std:; endl; } //线程B,读data { read_lock rlock(read_write_mutex); std::cout << data << std:; endl; } //线程C,写data { write_lock rlock(read_write_mutex); data = 2; }
通过 shared_lock 为 shared_mutex 上锁之后,线程将获得其共享锁,此时其他线程仍可以获得共享锁来读取 data,但是此时 unique_lock 将无法为 shared_mutex 上独占锁,功能1实现了。通过 unique_lock 为 shared_lock 上锁之后,线程将获得独占锁,此时无法再被上锁,功能2页实现了。