atomic MVar overwrite (was RE: [Haskell-cafe] How to use QSem?)

Simon Marlow simonmar at microsoft.com
Wed Jun 23 12:24:57 EDT 2004


On 23 June 2004 17:13, S. Alexander Jacobson wrote:

> Ah, that worked.  Thank you. The MVar
> documentation is also very brief.
> 
> I would also like to overwrite the contents of an
> MVar atomically regardless of whether it is full
> or empty.  I am current using.
> 
>   overWrite mvar val = tryTakeMVar mvar >> putMVar mvar val
> 
> But it is not atomic :-(  The lib functions
> (modifyMVar and tryPutMVar) are atomic but seem to
> require that you know in advance the MVar's state.

The question to ask here is "atomic with respect to what?".  modifyMVar
is atomic only with respect to other threads performing modifyMVar-type
operations on the MVar (i.e. take followed by put).  If another thread
is doing repeated puts into the MVar, then modifyMVar's atomicity is
defeated.

There isn't really a problem here, you just need to be sure that you use
your MVars in a consistent way - you can always define a new abstraction
that doesn't permit operations to be performed in the wrong order.

So in order to tell you how to write your overWrite function, we need to
know what other operations are being concurrently performed on the MVar,
and what invariants you expect to hold.

Cheers,
	Simon


More information about the Haskell-Cafe mailing list