[Haskell-cafe] MVars and locks
Alexander V Vershilov
alexander.vershilov at gmail.com
Thu May 7 12:20:44 UTC 2015
One of the good ways of thinking about MVars is to think about it
either like lock with value, or channel with one position.
And divide API into two parts.
In former case use operations: withMVar, modifyMVar, swapMVar,
readMVar (ghc>=7.8). This could be used for locking or keeping
mutable shared state.
In latter: takeMVar, putMVar, readMVar. This could be used for message
In any of this case you are safe from the situations mentioned above, however
if you use both, then you are in the grey area, and have to consider
About your question: yes another process could put value inside MVar and
your process will be locked unless somebody will read a value.
On 6 May 2015 at 22:19, Tom Ellis
<tom-lists-haskell-cafe-2013 at jaguarpaw.co.uk> wrote:
> In the following section of the book "Parallel and Concurrent Programming in
> 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?
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
More information about the Haskell-Cafe