From Operating System Concepts
In the solution to the first readers–writers problem, the reader processes share the following data structures:
- Why is
wait
/signal
onrw_mutex
guarded by semaphoremutex
?
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.
- In the structure of a reader process, Can I switch the order between updating
read_count
andwait
/signal
onrw_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.