3

I am trying to use boost::shared_mutex to implement a multiple-reader / single-writer mutex. My question is fairly simple, is it possible for a thread to gain reader access to a shared_mutex, when another thread tries to lock that shared_mutex for writing? For example, I have 10 threads, only one of them can write,

  • thread 1 has a shared_lock on that shared_mutex and tries to read something
  • thread 2 has a shared_lock on that shared_mutex and tries to read something
  • thread 3 has a unique_lock on that shared_mutex and tries to write something
  • thread 4 has a shared_lock on that shared_mutex and tries to read something
  • thread 5 has a shared_lock on that shared_mutex and tries to read something

The shared_mutex is currently shared locked by thread 2, my question is whether it is possible that thread 4 can gain read access to that shared_mutex, before thread 3 can write? Is it possible for a reader/writer mutex ever gets into a starvation situation, e.g., 100 reader v.s. 1 writer?

Thanks.

2

1 Answer 1

4

Apparently the boost::shared_mutex leaves the fairness policy up to the implementation. It can be either fair, reader-over-writer or writer-over-reader so depending on which it is for your particular version it's possible that the writer can be starved.

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

3 Comments

Tudor, can you tell me bit more more about "reader-over-writer" and "writer-over-reader"? Thanks.
reader-over-writer means that readers waiting to do shared_lock will have priority over writers waiting to do lock. writer-over-reader is the opposite.
When you say "boost::shared_mutex leaves the faireness policy up to the implementation" you probably meant to say that boost::shared_lock (and friends) leaves the fairness policy to the mutex implementation - boost::shared_mutex implements "reader-over-writer" policy (AFAIU). Is there a boost implementation for "writer-over-reader" mutex policy, or do I have to implement my own?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.