boost::shared_mutex multiple-reader / single-write

2019-07-07 19:33发布

问题:

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.

回答1:

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.