Search code examples
c++multithreadingboostmutexboost-thread

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


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 because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wait for the other threads to finish).

I think this is what boost::shared_mutex is supposed to do, but I'm not clear on how to use it, and haven't found a clear example.

Does anyone have a simple example I could use to get started?


Solution

  • It looks like you would do something like this:

    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
    }