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?
The shared_mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.
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.
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With