May periodic read locks in multiple threads completely stall writing thread for a long time?

55 views Asked by At
// thread function for readers
void func_readers()
{
    for (int i = 0; i < 1000000; ++i)
    {
        read_lock();
        //do some work;
    }
}

// thread function for writers
void func_writers()
{
    write_lock();
    // do some work;
}

Let's say there are 4 reader threads, and writer thread starts working. It stops, since there are 4 reading threads. When first reading thread finishes an iteration, it starts another one, and calls read_lock(). writing thread still waits, since there are 3 reading threads. Since there are no writing thread, first reading thread starts another iteration, and so on... Does this mean it's very likely that all 4 threads will do their work for 1000000 times, and only after that writing thread starts doing it's work?

1

There are 1 answers

1
Phil On

I believe in this situation, if the reader and writer threads share the same lock, the writer will still have a chance to write something. Think of it as this under the hood:

Let's say reader1 currently has the lock. Reader2, reader3, and reader4 are all on a queue waiting for the lock. It's at this point that writer also puts itself on the queue to wait for the lock. Once reader1 finishes, it releases the lock, and then puts itself back on the queue. However, note that at this point, it's on the queue after the writer.

Once reader2, reader3, and reader4 are popped off the queue and do their work, the writer will have the chance to acquire the lock.

Although this code isn't very efficient (it will basically run serially), it will work. Also, since you're on this topic, you should look into different implementations of reader/writer using multiple locks, counters, etc. :)