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.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
2607
  • 4,037
  • 13
  • 49
  • 64
  • Duplicate: http://stackoverflow.com/questions/4203467/multiple-readers-single-writer-locks-in-boost – Craig H Feb 21 '12 at 20:18
  • and here: http://stackoverflow.com/questions/989795/example-for-boost-shared-mutex-multiple-reads-one-write – Craig H Feb 21 '12 at 20:19

1 Answers1

3

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.

Tudor
  • 61,523
  • 12
  • 102
  • 142
  • Tudor, can you tell me bit more more about "reader-over-writer" and "writer-over-reader"? Thanks. – 2607 Feb 21 '12 at 21:13
  • 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. – Tudor Feb 21 '12 at 21:15
  • 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? – Guss Nov 12 '13 at 08:46