Multiple-readers, single-writer locks in Boost

前端 未结 3 589
温柔的废话
温柔的废话 2020-12-05 19:50

I\'m trying to implement the following code in a multithreading scenario:

Get shared access to mutex
Read data structure
If necessary:
   Get exclusive acces         


        
3条回答
  •  悲哀的现实
    2020-12-05 20:30

    Yes, you can do exactly what you want as shown in the accepted answer here. A call to upgrade to exclusive access will block until all readers are done.

    boost::shared_mutex _access;
    void reader()
    {
      // get shared access
      boost::shared_lock lock(_access);
    
      // now we have shared access
    }
    
    void writer()
    {
      // get upgradable access
      boost::upgrade_lock lock(_access);
    
      // get exclusive access
      boost::upgrade_to_unique_lock uniqueLock(lock);
      // now we have exclusive access
    }
    

提交回复
热议问题