Interruptibility and thread safeness with readMVar

Patrick Bosworth Patrick.Bosworth@jp.royalblue.com
Mon, 28 Oct 2002 18:01:29 +0900


How does the ghc run-time system determine if an operation is interruptible
when within "block" function scope? Explanations I've read in various
papers/web pages state that an operation is interruptible, even within a the
scope of the "block" function, if that operation can potentially block
waiting for input/output. Take the readMVar function. In my implementation
of ghc, readMVar is defined as follows.

readMVar :: MVar a -> IO a
readMVar m =
  block $ do
    a <- takeMVar m
    putMVar m a
    return a

Since, by the above definition of interruptible, both takeMVar and putMVar
are both interruptible operations, isn't there a possibility that, on
receipt of an exception while blocked on the "putMVar m a" operation, "MVar
m" would be left in an inconsistent state (i.e. empty)? Am I right in
thinking that readMVar should only ever be used when no other thread can
potentially access "MVar m"? Or have I completely missed the point?

My second question concerns readMVar directly. Is this function intended to
be an atomic operation in the context of multiple threads accessing the
"MVar m" parameter (i.e. thread safe)? Presumably, if a context switch takes
place after takeMVar but before putMVar, there is a possibility that another
thread will successfully evaluate putMVar on "MVar m", inserting a different
value. Is this intended? I suppose it's necessary to resort to some kind of
cunning ploy of using more MVars/threads to control access to MVar m if we
wan't to guarantee readMVar's thread safeness? If so, does anyone have such
an implementation?

Both of these questions are a result of trying to implement a function that
will atomically (in the presence of both other threads and asynchronous
exceptions) transfer the contents of one MVar to another (or leave both
MVars in their original states of the operation fails).


**********************************************************************
This message is intended only for the stated addressee(s)
and may be confidential. Access to this email by
anyone else is unauthorised. Any opinions expressed
in this email do not necessarily reflect the opinions of
royalblue. Any unauthorised disclosure, use of
dissemination, either whole or part is prohibited.

If you are not the intended recipient of this message,
please notify the sender immediately.
**********************************************************************