Silly question about IORefs and MVars

Simon Marlow simonmar@microsoft.com
Mon, 18 Nov 2002 11:22:41 -0000


> I have a silly question about IORefs and MVars.
>=20
> When do we have to use MVars if a var is accessed by multiple=20
> threads.=20
> In fact, I wonder why IORefs updates aren't safe :
> it seems that preemptive scheduling takes place during memory=20
> allocation=20
> and I can't see where there could be an allocation (and so a=20
> switch) in=20
> a read or a write of an IORef.

The problem is how to read the IORef, modify its contents, and write the
new value back without being preempted.  You can do this easily with an
MVar, but not an IORef.

> Related question : how less performant is a MVar comparated to simple=20
> ref.

reading/writing an MVar is an out-of-line call, whereas the IORef
operations are all inline.  I don't know the figures though.

Recently we added atomicModifyIORef which should allow IORefs to be used
in some cases where MVars were required before.  We haven't settled on
the exact interface yet, though.

Cheers,
	Simon