共享互斥变量shared_mutex允许线程获取多个共享所有权和一个专享所有权,即多个读进程一个写进程。
读锁定时使用boost::shared_lock<boost::shared_mutex>,写锁定时使用boost::unique_lock<boost::shared_mutex>。
#include <boost/thread.hpp> #include <boost/ref.hpp> #include <iostream> boost::mutex io_mu; class rw_data { private: int m_x; // 用于读写的数据 boost::shared_mutex rw_mu; // 共享互斥量 public: rw_data() :m_x(0){} void write() { boost::unique_lock<boost::shared_mutex> lock(rw_mu); // 写锁定 ++m_x; boost::mutex::scoped_lock io_lock(io_mu); std::cout << "write: " << m_x << std::endl; } void read(int *x) { boost::shared_lock<boost::shared_mutex> lock(rw_mu); // 读锁定 *x = m_x; } }; void writer(rw_data &data) // 写线程 { for (int i = 0; i < 10; ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(10)); // 睡眠 data.write(); } } void reader(rw_data &data) // 读线程 { int x; for (int i = 0; i < 10; ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(5)); // 睡眠 data.read(&x); boost::mutex::scoped_lock lock(io_mu); std::cout << "reader: " << x << std::endl; } } int main() { rw_data d; boost::thread_group pool; pool.create_thread(boost::bind(reader, boost::ref(d))); pool.create_thread(boost::bind(reader, boost::ref(d))); pool.create_thread(boost::bind(reader, boost::ref(d))); pool.create_thread(boost::bind(reader, boost::ref(d))); pool.create_thread(boost::bind(writer, boost::ref(d))); pool.create_thread(boost::bind(writer, boost::ref(d))); pool.join_all(); return 0; }