Boost logo

Threads-Devel :

Subject: Re: [Threads-devel] shared_mutex strategy
From: Anthony Williams (anthony_at_[hidden])
Date: 2010-05-18 17:10:33


On 18/05/10 21:28, Damien R. wrote:
> I looked in shared_mutex.hpp and I think you do not use writer or reader
> preference strategy.

Correct.

> The lock() method prevents new readers to acquire the mutex, and when
> the last reader release the mutex it notifies all readers and writers
> thread, so one writer or one reader will acquire the lock.
> If it is a reader, the writer will prevent other reader to acquire the
> lock.

When the last owner releases the mutex, all waiting threads are
notified. They will then compete for the ownership, and the OS will
decide which order they wake. This should mean that the highest priority
threads get preference. If a reader gets the lock first, then more
readers will be allowed to get the lock until a waiting writer wakes and
registers its intent.

> So, I want to know if what I said is correct, and if it is true, why do
> you have chose this implementation ?

I wanted one strategy rather than several, as then there is only one to
debug, and the previous implementation turned out to be buggy. This
seemed the most reasonable to me in that it avoids starvation of both
readers and writers, in exchange for slightly less concurrency on a
highly contended lock.

> Is it not possible to allow writer to acquire the lock when the last
> reader release the lock? And is it no possible to allow readers to
> acquire the lock when the writer release the lock ?

Yes, it's possible. This implementation doesn't do it.

I am currently of the opinion that a reader-writer mutex is a bad idea
anyway since it actually hinders scaling --- it's a more complicated
beast than a simple mutex, so locking and unlocking takes longer, and it
forms a point of contention between threads. Every thread that acquires
a lock has to modify the mutex, even if all threads are readers, and
that means the cache line holding the mutex has to ping pong between
processors. In low contention scenarios a simple mutex is simpler, and
probably faster. In high contention scenarios you probably ought to
change the design to reduce the contention.

The upshot of this is that I'm not going to change shared_mutex unless
it's actually broken.

Anthony

-- 
Author of C++ Concurrency in Action     http://www.stdthread.co.uk/book/
just::thread C++0x thread library             http://www.stdthread.co.uk
Just Software Solutions Ltd       http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

Threads-Devel list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk