Read write mutex in C++

10,110

Solution 1

Check out Dekker's algorithm.

Dekker's algorithm is the first known correct solution to the mutual exclusion problem in concurrent programming. The solution is attributed to Dutch mathematician Th. J. Dekker by Edsger W. Dijkstra in his manuscript on cooperating sequential processes. It allows two threads to share a single-use resource without conflict, using only shared memory for communication.

Note that Dekker's algorithm uses a spinlock (not a busy waiting) technique.
(Th. J. Dekker's solution, mentioned by E. W. Dijkstra in his EWD1303 paper) alt text

Solution 2

The short answer is that it is surprisingly difficult to roll your own read/write lock. It's very easy to miss a very subtle timing problem that could result in deadlock, two threads both thinking they have an "exclusive" lock, etc.

In a nutshell, you need to keep a count of how many readers are active at any particular time. Only when the number of active readers is zero, should you grant a thread write access. There are some design choices as to whether readers or writers are given priority. (Often, you want to give writers the priority, on the assumption that writing is done less frequently.) The (surprisingly) tricky part is to ensure that no writer is given access when there are readers, or vice versa.

There is an excellent MSDN article, "Compound Win32 Synchronization Objects" that takes you through the creation of a reader/writer lock. It starts simple, then grows more complicated to handle all the corner cases. One thing that stood out was that they showed a sample that looked perfectly good-- then they would explain why it wouldn't actually work. Had they not pointed out the problems, you might have never noticed. Well worth a read.

Hope this is helpful.

Share:
10,110
jasonline
Author by

jasonline

C++ Developer

Updated on June 25, 2022

Comments

  • jasonline
    jasonline almost 2 years

    This is an interview question. How do you implement a read/write mutex? There will be multiple threads reading and writing to a resource. I'm not sure how to go about it. If there's any information needed, please let me know.

    Update: I'm not sure if my statement above is valid/understandable. But what I really want to know is how do you implement multiple read and multiple writes on a single object in terms of mutex and other synchronization objects needed?

  • Matt Joiner
    Matt Joiner about 14 years
    i like that you just answered the question, instead of getting into OS nitty gritty :)
  • jasonline
    jasonline about 14 years
    ShellShock: Can a read/write mutex not be implemented in terms of a regular mutex and a semaphore perhaps? I'm not familiar with semaphores but I got a feeling the interviewer is leading me to that solution.
  • jasonline
    jasonline about 14 years
    Any example for off-the-shelf solutions you can recommend?