Semaphore solution to reader-writer: order between updating reader count and waiting or signaling on read/write binary semaphore?

↘锁芯ラ 提交于 2019-12-02 12:51:16
  1. Why is wait/signal on rw_mutex guarded by semaphore mutex?

Imagine it's not, i.e. only read_count lines are guarded, and that you have reader threads α and β.

α increases read_count, executes signal(mutex), and goes to executing if (read_count == 1), and — bah! — CPU scheduler decides "enough, let other threads to have a fun too!", and starts executing thread β.

Thread β locks mutex, increases read_count, releases mutex, and also starts executing if (read_count == 1). Now, because read_count is 2, comparisons in both threads fails, so none of readers take the rw_mutex, and your writer goes writing over the data being read.

  1. In the structure of a reader process, Can I switch the order between updating read_count and wait/signal on rw_mutex, as following?

Yes, you can. The distinction is purely semantical: the original reads as "We're about to read, so increase read_count, and if we're the only reader, lock rw_mutex. Perform reading. Then, as we're done, decrease read_count, and if we were the last reader, unlock rw_mutex".

Your variant reads as "if nobody reads, lock rw_mutex. Then increase read_count. Perform reading. Then, if we were the only reader, unlock rw_mutex. Decrease read_count".


It might out of slight interest though, that if the author have used your variant, my answer to the first question would've been a bit longer because additionally, in the part of code with signal(rw_mutex), you could've get a deadlock :Ь

Also, the concept author is describing in C++ is the std::shared_mutex.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!