[Haskell-cafe] MVar style question

Roberto Zunino zunino at di.unipi.it
Thu Jan 4 16:23:43 EST 2007


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.


More information about the Haskell-Cafe mailing list