Example for boost shared_mutex (multiple reads/one write)?

前端 未结 6 1532
旧时难觅i
旧时难觅i 2020-11-22 12:48

I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it\'s expensive bec

6条回答
  •  无人及你
    2020-11-22 13:31

    1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.

    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
    }
    

    Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.

提交回复
热议问题