Search code examples
multithreadingconcurrencysynchronizationsemaphore

Readers-writer lock (writer preferred) implementation


I've read up on Readers-writer lock on wiki - https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock but tried using only one counter and one lock.

I'm curious to know whether this implementation is valid. If yes, do you think this would be enough for a technical interview.

            read() {
                lock g;
                while (num_of_writers > 0) {
                    g.wait(); // always yield to writers
                }
                doRead();
                unlock g;
            }

            write() {
                lock g;
                numOfWriters++; // let all the writers to queue up here
                unlock g;

                lock g;
                doWrite();
                num_of_writers--;
                g.notify();
                unlock g;
            }




Solution

  • Your implementation looks like it correctly implements a valid lock, but it does not reliably prioritize writers (as stated in your title).

    In particular, imagine doWrite() is a long-running operation currently executing with num_of_writers==1. During its execution many new reader and writer threads arrive at a read() or write() call. When the current writer unlocks g, there may be several writers queued up on their first lock g statement, but those writers are not given priority over readers who are queued at lock g or g.wait(). In fact depending on the implementation of the notify/wait condition variable, priority might actually be given to readers at g.wait().

    Also (and perhaps most importantly), this code does not allow for concurrent reads (doRead() executes inside a critical section of g), so this is not even technically a reader-writer lock.

    Wrt technical interview, it's a decent counter-example... Give points to the candidate who can name these defects within a few minutes, and hire the one who can fix them ;-)