[Haskell-cafe] readMVar and the devils

Benjamin Franksen benjamin.franksen at bessy.de
Tue Jul 6 05:32:01 EDT 2004

On Friday 02 July 2004 15:59, you wrote:
> > at a guess the magic take put is:
> >
> > block ( do
> > a <- takeMVar x
> > putMVar x a
> > )
> > return a
> This doesn't prevent the race condition Conor mentioned. It only
> prevents the thread executing the above code from being interrupted
> by an asynchronous exception (i.e., Control-C, or another thread
> killing this one). The only way to prevents race conditions is
> through discipline (take then put is one example). 

True, but it's not the whole thruth.

Is the next thing i'm going to hear "Haskell is a language for the 
mature programmer" (~= what people who don't know better use to say 
about C)? The great Pure Functional Language Haskell with the dead-safe 
static type system (including all those sexy types) gives the 
programmer nothing more to cope with concurrency than low-level MVars 
together with imperative style programming.(?!?)

Seriously: What the original poster needs is not discipline but a 
suitable abstraction built on top of MVar. Like:

module MEVar (
  MEVar, -- abstract
  ) where

-- The 'E' in MEVar stands for 'exclusive read'
-- There are probably better names for this

import Control.Concurrent

newtype MEVar a = MVar (MVar a)

readMEVar :: MEVar a -> IO a
readMEVar outer = do
  inner <- takeMVar outer
  value <- takeMVar inner
  putMVar inner value
  putMVar outer inner
  return value



More information about the Haskell-Cafe mailing list