Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 equivalent to boost shared_mutex

Is there a C++11 equivalent for the boost::shared_mutex. Or another solution to handle a multiple reader / single writer situation in C++11?

like image 476
Haatschii Avatar asked Jan 13 '13 18:01

Haatschii


People also ask

What is Shared_mutex?

The shared_mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

When to use shared_ mutex?

Shared mutexes are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do so.

What is shared lock in C++?

The class shared_lock is a general-purpose shared mutex ownership wrapper allowing deferred locking, timed locking and transfer of lock ownership. Locking a shared_lock locks the associated shared mutex in shared mode (to lock it in exclusive mode, std::unique_lock can be used)


2 Answers

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

like image 189
Howard Hinnant Avatar answered Sep 20 '22 22:09

Howard Hinnant


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.

like image 24
Sean Cline Avatar answered Sep 19 '22 22:09

Sean Cline