[Haskell-cafe] Shared/Exclusive Locks

Robert Dockins robdockins at fastmail.fm
Wed Dec 28 12:00:54 EST 2005


On Dec 28, 2005, at 11:14 AM, 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".
>
> -- 
> Chris

This seems fine for STM because you can just retry until count is 0,  
but I don't know of a good way to wait for an MVar to have a  
particular value (I assume busy-wait isn't what you have in mind).   
You'll probably need an additional MVar that exclusive lockers "take"  
to let them block.  Then you need to be sure that this MVar is filled  
when count goes to 0 and empty when count goes above zero.


Rob Dockins

Speak softly and drive a Sherman tank.
Laugh hard; it's a long way to the bank.
           -- TMBG





More information about the Haskell-Cafe mailing list