Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::unique_lock and boost::shared_lock for reader writer locks

We have implemented a reader writer lock with

 typedef boost::unique_lock<boost::shared_mutex> WriterLock;
 typedef boost::shared_lock<boost::shared_mutex> ReadersLock;

where we have many multithreaded readers and only a few writers. Readers share access with other readers but block on a writer. Writer blocks until it has exclusive access to the resource.

We could not find this in the boost documentation... What is the policy to prevent Writer starvation?
For example if there are many readers all pounding the lock from a thread pool, is there any guarantee upper limit on number of lock tries before the writer finally acquires the lock?

We been seeing performance numbers that seem to indicate the write has to wait until there are no readers at all and there are rare cases where that is a long time, since new readers can request locks while the current readers are being serviced. In that case it seems that in our code the writer is has to wait a very long time until there are no reads at all.

We would prefer a more queue like system, where when a writer request a lock, all the current readers drain out but all new incoming readers block behind the writer request.

What is the behavior of the upgradeable lock concept in Boost? Boost threads

Its does not say either way how it handles writer starvation.

like image 356
meissnersd Avatar asked Nov 13 '22 19:11

meissnersd


1 Answers

A small improvement on @Guerrero's solution that increases the fairness for multiple readers and multiple writers so no one would starve to death:

read() {
    while (atomic-write-requests > 0)
        condition.wait();
    ReadersLock lock(acquireReaderLock());
    doRead();
}
write() {
    while (atomic-write-requests > 0)
        condition.wait();
    atomic-write-requests++;
    WritersLock lock(acquireWriterLock());

    doWrite();
    atomic-write-requests--;
    condition.notify();
}

In this solution, a new and fair competition will start every time a writer leaves the scope.

like image 135
Shloim Avatar answered Nov 15 '22 13:11

Shloim