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....?

5
  • i.e. use Boost for now. Possibly migrate to C++14 if it gets incorporated in that standard. Commented Aug 11, 2014 at 10:38
  • 1
    This 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. Commented Aug 11, 2014 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. Commented Aug 11, 2014 at 10:44
  • 2
    Because std::mutex is standard in C++11, but Boost is not. Commented Aug 11, 2014 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) Commented Aug 11, 2014 at 13:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

True. The boost internal implementation includes the mutex itself and 3 condition variables. Quite heavy pattern if you need simple lock.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.