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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With