亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

例如Boost Shared_mutex(多次讀取/一次寫入)?

例如Boost Shared_mutex(多次讀取/一次寫入)?

C++
慕工程0101907 2019-07-08 16:28:52
例如Boost Shared_mutex(多次讀取/一次寫入)?我有一個多線程應用程序,必須經常讀取一些數據,偶爾也會更新這些數據?,F在,互斥鎖保持了對該數據的安全訪問,但是代價很高,因為我希望多個線程能夠同時讀取,并且只在需要更新時將它們鎖定(更新線程可以等待其他線程完成)。我想這就是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}


查看完整回答
反對 回復 2019-07-08
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

1800條信息或多或少是正確的,但有幾個問題我想糾正。

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}

另外,與Shared_lock不同,只有單個線程可以一次獲得升級鎖,即使它沒有升級(當我遇到它時,我覺得很尷尬)。因此,如果您的所有讀者都是條件作者,則需要找到另一種解決方案。


查看完整回答
反對 回復 2019-07-08
?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

您可以使用Boost創建讀寫鎖:

#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}


查看完整回答
反對 回復 2019-07-08
  • 3 回答
  • 0 關注
  • 999 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號