C++11 equivalent to boost shared_mutex

I tried but failed to get shared_mutex into C++11. It has been proposed for a future standard. The proposal is here.

Edit: A revised version (N3659) was accepted for C++14.

Here is an implementation:

http://howardhinnant.github.io/shared_mutex

http://howardhinnant.github.io/shared_mutex.cpp


Simple... There isn't one. There is no standard C++ implementation of a readers-writer lock.

But, you have a few options here.

  1. You are left at your own devices to make your own readers-writer lock.
  2. Use a platform-specific implementation such as Win32's, POSIX's, or Boost's as you mention.
  3. Don't use one at all -- use a mutex which already exists in C++11.

Going with #1 and implementing your own is a scary undertaking and it is possible to riddle your code with race conditions if you don't get it right. There is a reference implemenation that may make the job a bit easier.

If you want platform independent code or don't want to include any extra libraries in your code for something as simple as a reader-writer lock, you can throw #2 out the window.

And, #3 has a couple caveats that most people don't realize: Using a reader-writer lock is often less performant, and has more difficult-to-understand code than an equivalent implementation using a simple mutex. This is because of the extra book-keeping that has to go on behind the scenes of a readers-writer lock implementation.


I can only present you your options, really it is up to you to weigh the costs and benefits of each and pick which works best.


Edit: C++17 now has a shared_mutex type for situations where the benefits of having multiple concurrent readers outweigh the performance cost of the shared_mutex itself.