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

前端 未结 1 520
花落未央
花落未央 2021-01-27 11:24

From Operating System Concepts

In the solution to the first readers–writers problem, the reader processes share the following data structures:

         


        
相关标签:
1条回答
  • 2021-01-27 11:56
    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.

    0 讨论(0)
提交回复
热议问题