C++17 std::shared_mutex的替代方案boost::shared_mutex

std::shared_mutex

http://en.cppreference.com/w/cpp/thread/shared_mutex

 

GCC5.1才会支持C++17 std::shared_mutex,替代方案是boost::shared_mutex

 

boost::shared_mutex官方文档:http://www.boost.org/doc/libs/1_60_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex

 

需要的lib:

#pragma comment(lib, "libboost_chrono-vc140-mt-1_60.lib")
#pragma comment(lib, "libboost_date_time-vc140-mt-1_60.lib")
#pragma comment(lib, "libboost_system-vc140-mt-1_60.lib")
#pragma comment(lib, "libboost_system-vc140-mt-1_60.lib")
#pragma comment(lib, "libboost_thread-vc140-mt-1_60.lib")

 

 

boost::shared_mutex用法示例:

参考自:http://stackoverflow.com/questions/3896717/example-of-how-to-use-boost-upgradeable-mutexes

#include <boost/thread/locks.hpp>  
#include <boost/thread/shared_mutex.hpp>  

int
main()
{
    typedef boost::shared_mutex Mutex;
    typedef boost::shared_lock<Mutex> ReadLock;
    typedef boost::unique_lock<Mutex> WriteLock;
    Mutex mutex;

    {
        // acquire read lock
        ReadLock read( mutex );

        // do something to read resource
    }

    {
        // acquire write lock
        WriteLock write( mutex, boost::adopt_lock_t() );

        // do something to write resource
    }
}

 

 参考自:http://stackoverflow.com/questions/989795/example-for-boost-shared-mutex-multiple-reads-one-write

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
}

 

其他参考:

How to make a multiple-read/single-write lock from more basic synchronization primitives?

http://stackoverflow.com/questions/27860685/how-to-make-a-multiple-read-single-write-lock-from-more-basic-synchronization-pr

猜你喜欢

转载自aigo.iteye.com/blog/2291862