[Haskell-cafe] Shared/Exclusive Locks

Chris Kuklewicz haskell at list.mightyreason.com
Wed Dec 28 11:40:57 EST 2005


Hi,

"The little book of semaphones" (287 pages) is available at
http://greenteapress.com/semaphores/

It has a slightly better solution that uses two mutexes and a count, see
the Readers-writers problem, section 4.2 page 67 (pdf page 79).  It also
goes on to discuss fairness and starvation and writer (i.e. exclusive)
priority.

-- 
Chris

Chris Kuklewicz wrote:
> John Goerzen wrote:
> 
>>Hello,
>>
>>I have the need for a locking object that can provide shared and
>>exclusive locks in much the same manner as the POSIX flock() function.
>>
>>A thread that acquires an exclusive lock has a guarantee that no other
>>thread holds any locks.
>>
>>A thread that acquires a shared lock has a guarantee that no other
>>thread holds an exclusive lock, though any number of other threads hold
>>shared locks.
>>
>>My intuition tells me that this could be implemented in terms of an MVar
>>somehow.  (At least, I've used MVars for simple locks for quite some
>>time.)  But I can't quite figure out how.  Any ideas?
>>
>>Thanks,
>>
>>-- John
> 
> 
> STM or IO ?
> 
> You need a count of shared locks "S", *Var Word32.
> 
> To increase the count "S", you need to hold a mutex "E", *Var ().
> So (take mutex "E" >> increment "S" >> release "E") is the the combined
> operation.
> 
> To decrease the count "S", you do not need to hold a mutex. (decrement "S").
> 
> By grabbing the mutex "E" and waiting for "S" to go to zero, you have
> acquired exclusive control.  When you are done just release "E".
> 



More information about the Haskell-Cafe mailing list