[Haskell-cafe] Shared/Exclusive Locks
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:
>> I have the need for a locking object that can provide shared and
>> exclusive locks in much the same manner as the POSIX flock()
>> A thread that acquires an exclusive lock has a guarantee that no
>> 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
>> 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?
>> -- 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
> 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".
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.
Speak softly and drive a Sherman tank.
Laugh hard; it's a long way to the bank.
More information about the Haskell-Cafe