[Haskell-cafe] Implementing tryReadMVar

Jan-Willem Maessen - Sun Labs East Janwillem.Maessen at Sun.COM
Wed Sep 1 13:09:44 EDT 2004

Einar Karttunen wrote:
> There are several cases in which multiple threads racing putMVar is
> correct. Consider e.g. a server thread encapsulating state, which 
> needs to rate limit its clients. The server is put behind a MVar
> to which all the clients putMVar and thus block until the server 
> is ready
 > ...
> The server thread uses tryTakeMVar for its job. 
> Now add a debug function:
> debug :: MVar SCoreT -> IO ()
> debug mv = tryReadMVar mv >>= maybe (putStrLn "Nothing") print
> And suddenly we have a created a subtle bug in the code with 
> flawed tryReadMVar implementation.

Indeed, but depending upon the vagaries of scheduling, you may in fact 
be guaranteed *never* to see any output (eg, when tryTakeMVar yields 
on empty and putMVar yields unconditionally).

I was, however, curious what use you had in mind where writes were 
racing, but where you nonetheless wanted to perform blind non-blocking 
reads.  Such situations are generally fraught with peril.  In this 
case, the peril is starvation of the debug thread---which you may or 
may not actually care about.

-Jan-Willem Maessen

More information about the Haskell-Cafe mailing list