[Haskell-cafe] MVars and locks

Ben Franksen ben.franksen at online.de
Sat Jul 4 13:38:04 UTC 2015


Tom Ellis wrote:
> In the following section of the book "Parallel and Concurrent Programming
> in Haskell"
> 
>     
http://chimera.labs.oreilly.com/books/1230000000929/ch07.html#sec_conc-phonebook
> 
> Simon Marlow explains that MVars can be used to implement something like
> locks on shared functional state: "To acquire the lock, we take the MVar,
> whereas, to update the variable and release the lock, we put the MVar."
> 
> Am I right in thinking this only holds if we are careful to ensure both
> those operations happen in the given order?
> 
> For example, if I take the MVar (lock) and I am about to put something
> back in (unlock) but someone else puts something in before I do, then the
> lock
> system becomes broken, doesn't it?  So if we want to be sure we have a
> robust lock system we have to wrap up MVars in another abstraction?

You are absolutely right. It's exactly the same as with the more traditional 
semaphores, i.e. locking happens if and only if all involved parties adhere 
to the protocol (take lock; do something; give lock). It is usually best to 
enforce adherence to the protocol on the module level by not exporting 
anything that exposes the MVar itself (and using bracket or, even better, 
withMVar or modifyMVar internally).

Cheers
Ben
-- 
"Make it so they have to reboot after every typo." ― Scott Adams




More information about the Haskell-Cafe mailing list