Re: [Haskell] IVar

Jan-Willem Maessen wrote:
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.
Ah, so I was thinking of the following readIVar: readIVar = unsafePerformIO . readIVarIO But clearly there's a better one. Fair enough. Cheers, Simon

On Dec 5, 2007, at 3:58 AM, Simon Marlow wrote:
Jan-Willem Maessen wrote:
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.
Ah, so I was thinking of the following readIVar:
readIVar = unsafePerformIO . readIVarIO
But clearly there's a better one. Fair enough.
Hmm, so unsafePerformIO doesn't deal with any operation that blocks? I'm wondering about related sorts of examples now, as well: do x <- newIVar y <- unsafeInterleaveIO (readIVarIO x) writeIVar x 3 print y Or the equivalent things to the above with MVars. -Jan
Cheers, Simon

Jan-Willem Maessen wrote:
On Dec 5, 2007, at 3:58 AM, Simon Marlow wrote:
Ah, so I was thinking of the following readIVar:
readIVar = unsafePerformIO . readIVarIO
But clearly there's a better one. Fair enough.
Hmm, so unsafePerformIO doesn't deal with any operation that blocks?
Well, operations that block inside unsafePerformIO do block the whole thread, yes, and that may lead to a deadlock if the blocking operation is waiting to be unblocked by its own thread. It sounds like you want to back off from any earlier-than-necessary evaluation at this point. Fortunately this problem doesn't arise, because GHC won't commute evaluation past an IO operation.
I'm wondering about related sorts of examples now, as well:
do x <- newIVar y <- unsafeInterleaveIO (readIVarIO x) writeIVar x 3 print y
Or the equivalent things to the above with MVars.
Yes, this suffers from the same problem. If the compiler were to eagerly evaluate y, then you'll get deadlock. Cheers, Simon
participants (2)
-
Jan-Willem Maessen
-
Simon Marlow