[Haskell] IVar

Jan-Willem Maessen jmaessen at alum.mit.edu
Tue Dec 4 12:02:27 EST 2007

On Dec 4, 2007, at 8:53 AM, Simon Marlow wrote:

> Rishiyur Nikhil wrote:
>> Simon Peyton-Jones said:
>> >  But since the read may block, it matters *when* you perform it.
>> >  For example if you print "Hello" and then read the IVar, you'll
>> >  block after printing; but if you read the IVar and then print, the
>> >  print won't come out.  If the operation was pure (no IO) then  
>> you'd
>> >  have a lot less control over when it happened.
>> But this is true of any expression in a non-strict language.
>> Why the special treatment of IVars?
> Consider this:
> do
>    x <- newIVar
>    let y = readIVar x
>    writeIVar x 3
>    print y
> (I wrote the let to better illustrate the problem, of course you can  
> inline y if you want).  Now suppose the compiler decided to evaluate  
> y before the writeIVar.  What's to prevent it doing that?  Nothing  
> in the Haskell spec, only implementation convention.

Nope, semantics.  If we have a cyclic dependency, we have to respect  
it---it's just like thunk evaluation order in that respect.  If we  
decide to do the evaluation eagerly, we have to be prepared to bail  
out when the information we require is not available to us.  The  
easiest expedient from GHC's perspective is to perform the evaluation  
lazily, just as we'd expect.

>  GHC will not transform the program in this way, because it can have  
> some other undesirable effects.  e.g. see
>  http://hackage.haskell.org/trac/ghc/ticket/1592
> A pure readIVar would be just like lazy I/O, with similar  
> drawbacks.  With readIVar, the effect that lets you observe the  
> evaluation order is writeIVar; with hGetContents it is hClose.   
> Conclusion: it's probably no worse than lazy I/O.

Actually, it's considerably better.  The only thing we can observe is  
that the implementation failed to respect the desired semantics (which  
state that computation blocks until the value is available).  That  
causes problems with the strictness properties of I/O, but everything  
to do with the strictness properties of I/O is problematic (because we  
have to decide whether exit = _|_ or not as the above report notes).   
It doesn't, so far as I can see, cause problems with the strictness  
properties of pure computations except that a thread can block in the  
middle of a pure computation waiting for an IVar to fill.  Possibly  
tricky from an RTS perspective, but there's no *semantic* problem.


> Cheers,
> 	Simon
> _______________________________________________
> Haskell mailing list
> Haskell at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell

More information about the Haskell mailing list