[Haskell-cafe] Implementing tryReadMVar

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

Einar Karttunen wrote:
> Hello
> Is it possible to implement an operation like 
> tryReadMVar :: MVar a -> IO (Maybe a)
> in a good fashion? The semantics should be 
> "Read the value of the MVar without taking
> it if it is filled, otherwise return Nothing".
> There are several easy and flawed implementations:
> ...
> tryReadMVar mv = do mc <- tryTakeMVar mv
>                     case mc of
>                      Nothing -> return mc
>                      Just v  -> putMVar mv v >> return mc
> Now this can block on the putMVar if there was a thread switch 
> and someone filled the MVar behind our back. 

This sets off alarm bells in my head.  What are you actually trying to 
do, and why is correct for mutiple threads to race to "putMVar"?

Like locks, MVars require a certain discipline of usage (though 
several such disciplines are possible for MVars, whereas with locks 
you pretty much want to nest them in lock/unlock pairs).  I'm curious 
which discipline you are actually trying to use.

-Jan-Willem Maessen

More information about the Haskell-Cafe mailing list