C++11 equivalent to boost shared_mutex

前端 未结 3 1406
日久生厌
日久生厌 2020-11-28 06:04

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?

3条回答
  •  时光说笑
    2020-11-28 06:19

    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.

提交回复
热议问题