例如Boost Shared_mutex(多次读取/一次写入)?我有一个多线程应用程序,必须经常读取一些数据,偶尔也会更新这些数据。现在,互斥锁保持了对该数据的安全访问,但是代价很高,因为我希望多个线程能够同时读取,并且只在需要更新时将它们锁定(更新线程可以等待其他线程完成)。我想这就是boost::shared_mutex应该这样做,但我不清楚如何使用它,而且还没有找到一个明确的例子。有人可以用一个简单的例子来开始吗?
3 回答
牛魔王的故事
TA贡献1830条经验 获得超3个赞
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}
守着一只汪
TA贡献1872条经验 获得超3个赞
boost::shared_mutex _access;void reader(){ boost::shared_lock< boost::shared_mutex > lock(_access); // do work here, without anyone having exclusive access}void conditional_writer(){ boost::upgrade_lock< boost::shared_mutex > lock(_access); // do work here, without anyone having exclusive access if (something) { boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock); // do work here, but now you have exclusive access } // do more work here, without anyone having exclusive access}void unconditional_writer(){ boost::unique_lock< boost::shared_mutex > lock(_access); // do work here, with exclusive access}
白衣染霜花
TA贡献1796条经验 获得超10个赞
#include <boost/thread/locks.hpp>#include <boost/thread/shared_mutex.hpp>typedef boost::shared_mutex Lock;typedef boost: :unique_lock< Lock > WriteLock;typedef boost::shared_lock< Lock > ReadLock;Lock myLock;void ReadFunction(){ ReadLock r_lock(myLock); //Do reader stuff}void WriteFunction(){ WriteLock w_lock(myLock); //Do writer stuff}
- 3 回答
- 0 关注
- 965 浏览
添加回答
举报
0/150
提交
取消