[Haskell-cafe] MVar style question

Chad Scherrer chad.scherrer at gmail.com
Fri Jan 5 10:15:34 EST 2007


Thanks, you make some interesting points to consider. This leads me to
wonder how these arguments might be extended to

(1) IORef (a,b)     vs.     (IORef a, IORef b)
(2) TVar (a,b)     vs.     (TVar a, TVar b)

On 1/4/07, Roberto Zunino <zunino at di.unipi.it> wrote:
> Chad Scherrer wrote:
> > When using MVars, is there a reason to prefer using MVar (a,b) over
> > (MVar a, MVar b), or vice versa?
>
> No one is strictly better than the other. But there are practical
> implications of choosing between them.
>
> For instance, MVar (A,B) is less prone to deadlock issues than (MVar A,
> MVar B). Consider
>
>     (a,b) :: (MVar A, MVar B)
>
>     alice = do takeMVar a ; takeMVar b ; foo ; putMVar a x ; putMVar b y
>     bob   = do takeMVar b ; takeMVar a ; bar ; putMVar b w ; putMVar a z
>
> If alice and bob run concurrently, it might happen that alice takes a,
> bob takes b, and no one can proceed further. So, you must be very
> careful about the ordering of the takeMVar's (e.g. if you need both,
> always take a before taking b). There is no such issue using MVar (A,B),
> since only a single takeMVar is needed.
>
> On the other hand using MVar (A,B) may reduce concurrency, imposing
> unnecessary locks. If alice2 only needs a, why should she be blocked
> from bob2 using only b? This issue gets worse once one starts using MVar
> (A,B,C,...), or MVar [A].
>
> So, the solution is: choose wisely! ;-)
>
> Regards,
> Roberto Zunino.
>


-- 

Chad Scherrer

"Time flies like an arrow; fruit flies like a banana" -- Groucho Marx


More information about the Haskell-Cafe mailing list