例如Boost Shared_mutex(多次读取/一次写入)?

例如Boost Shared_mutex(多次读取/一次写入)?

我有一个多线程应用程序,必须经常读取一些数据,偶尔也会更新这些数据。现在,互斥锁保持了对该数据的安全访问,但是代价很高,因为我希望多个线程能够同时读取,并且只在需要更新时将它们锁定(更新线程可以等待其他线程完成)。

我想这就是boost::shared_mutex应该这样做,但我不清楚如何使用它,而且还没有找到一个明确的例子。

有人可以用一个简单的例子来开始吗?


慕工程0101907
浏览 970回答 3
3回答

牛魔王的故事

看起来你会做这样的事:boost::shared_mutex&nbsp;_access;void&nbsp;reader(){ &nbsp;&nbsp;//&nbsp;get&nbsp;shared&nbsp;access &nbsp;&nbsp;boost::shared_lock<boost::shared_mutex>&nbsp;lock(_access); &nbsp;&nbsp;//&nbsp;now&nbsp;we&nbsp;have&nbsp;shared&nbsp;access}void&nbsp;writer(){ &nbsp;&nbsp;//&nbsp;get&nbsp;upgradable&nbsp;access &nbsp;&nbsp;boost::upgrade_lock<boost::shared_mutex>&nbsp;lock(_access); &nbsp;&nbsp;//&nbsp;get&nbsp;exclusive&nbsp;access &nbsp;&nbsp;boost::upgrade_to_unique_lock<boost::shared_mutex>&nbsp;uniqueLock(lock); &nbsp;&nbsp;//&nbsp;now&nbsp;we&nbsp;have&nbsp;exclusive&nbsp;access}

守着一只汪

1800条信息或多或少是正确的,但有几个问题我想纠正。boost::shared_mutex&nbsp;_access;void&nbsp;reader(){ &nbsp;&nbsp;boost::shared_lock<&nbsp;boost::shared_mutex&nbsp;>&nbsp;lock(_access); &nbsp;&nbsp;//&nbsp;do&nbsp;work&nbsp;here,&nbsp;without&nbsp;anyone&nbsp;having&nbsp;exclusive&nbsp;access}void&nbsp;conditional_writer(){ &nbsp;&nbsp;boost::upgrade_lock<&nbsp;boost::shared_mutex&nbsp;>&nbsp;lock(_access); &nbsp;&nbsp;//&nbsp;do&nbsp;work&nbsp;here,&nbsp;without&nbsp;anyone&nbsp;having&nbsp;exclusive&nbsp;access &nbsp;&nbsp;if&nbsp;(something)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;boost::upgrade_to_unique_lock<&nbsp;boost::shared_mutex&nbsp;>&nbsp;uniqueLock(lock); &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;do&nbsp;work&nbsp;here,&nbsp;but&nbsp;now&nbsp;you&nbsp;have&nbsp;exclusive&nbsp;access &nbsp;&nbsp;} &nbsp;&nbsp;//&nbsp;do&nbsp;more&nbsp;work&nbsp;here,&nbsp;without&nbsp;anyone&nbsp;having&nbsp;exclusive&nbsp;access}void&nbsp;unconditional_writer(){ &nbsp;&nbsp;boost::unique_lock<&nbsp;boost::shared_mutex&nbsp;>&nbsp;lock(_access); &nbsp;&nbsp;//&nbsp;do&nbsp;work&nbsp;here,&nbsp;with&nbsp;exclusive&nbsp;access}另外,与Shared_lock不同,只有单个线程可以一次获得升级锁,即使它没有升级(当我遇到它时,我觉得很尴尬)。因此,如果您的所有读者都是条件作者,则需要找到另一种解决方案。

白衣染霜花

您可以使用Boost创建读写锁:#include&nbsp;<boost/thread/locks.hpp>#include&nbsp;<boost/thread/shared_mutex.hpp>typedef&nbsp;boost::shared_mutex&nbsp;Lock;typedef&nbsp;boost: :unique_lock<&nbsp;Lock&nbsp;>&nbsp;WriteLock;typedef&nbsp;boost::shared_lock<&nbsp;Lock&nbsp;>&nbsp;ReadLock;Lock&nbsp;myLock;void&nbsp;ReadFunction(){ &nbsp;&nbsp;&nbsp;&nbsp;ReadLock&nbsp;r_lock(myLock); &nbsp;&nbsp;&nbsp;&nbsp;//Do&nbsp;reader&nbsp;stuff}void&nbsp;WriteFunction(){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WriteLock&nbsp;w_lock(myLock); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Do&nbsp;writer&nbsp;stuff}
打开App,查看更多内容
随时随地看视频慕课网APP