6

My understanding is: std::mutex blocks other threads no matter if they want to read or write, whereas boost::shared_mutex will allow multiple reads.

So my question is, should I always prefer a boost::shared_mutex instead of a normal std::mutex to allow the possibility of parallel reads to take place? Using a normal std::mutex feels like I am denying some possible read throughput....?

quantdev
  • 23,517
  • 5
  • 55
  • 88
user997112
  • 29,025
  • 43
  • 182
  • 361
  • i.e. use Boost for now. Possibly migrate to C++14 if it gets incorporated in that standard. – Bathsheba Aug 11 '14 at 10:38
  • 1
    [This](http://permalink.gmane.org/gmane.comp.lib.boost.devel/211180) is relevant. Briefly, `shared_mutex` is more costly to lock than a plain one, and can be a source of contention if your readers are only locking for a short period of time. – T.C. Aug 11 '14 at 10:39
  • @Bathsheba Not quite a dup. This question asks if there's any reason to prefer a plain mutex over a shared one. That question asks if there's a standardized `shared_mutex`. – T.C. Aug 11 '14 at 10:44
  • 2
    Because `std::mutex` is standard in C++11, but Boost is not. – Basile Starynkevitch Aug 11 '14 at 10:51
  • As unfortunate as it is, it is not possible to counter a close vote, you can only re-open closed questions. Thus, unless 3 more close votes are cast and the question is then re-opened, those 2 votes will stay... just ignore them. (note: if you know of similar questions, it is worth linking to them from your own question and clearly state why they differ) – Matthieu M. Aug 11 '14 at 13:20

1 Answers1

7

I can't speak to the performance between the two of them, but my guess is that because of the extra logic boost::shared_mutex might be slower. Asides from that, depending on how many readers you have you might block the writing thread longer than you would want as it would have to wait until all the read accesses are done.

ikh
  • 10,119
  • 1
  • 31
  • 70
Harald Scheirich
  • 9,676
  • 29
  • 53
  • 4
    True. The boost internal implementation includes the mutex itself and 3 condition variables. Quite heavy pattern if you need simple lock. – Tanuki Aug 11 '14 at 10:51