isEmptyChan blocks?

Volker Stolz vs@foldr.org
Mon, 30 Jun 2003 12:29:30 +0200


Am 23. Jun 2003 um 12:05 CEST schrieb Simon Marlow:
> Could you explain how this works?  writeChan doesn't update the count -
> it should, right?  But if it does, won't there be race conditions when
> read & write happen at the same time?

I updated the file at http://www.foldr.org/~stolz/Chan2.hs with the promised
documentation. Regarding 'correctness', I quote from the introduction:

-- There's a small race when concurrently reading from a channel and obtaining
-- the count: the item might be already read but the count hasn't been updated
-- yet. But hey, this is Concurrent Haskell so the number of elements has rather
-- informational value by the time you see it, anyway. There is no such race
-- condition on writing:
--  1) write vs. getCount: The writer locks all count-MVars before writing and
--       only releases them with the new value when the new item is in place
--     ==> reported count will be correct w.r.t. the above readChan/count-race.
--  2) write vs. read: Because the writer holds the count-MVars until after the
--       new item is in place, the reader has to wait for the updated count,
--       although it immediately obtains the item from the stream.
-- Overall conclusion: 'getCountChan' will report either the actual number of items
-- in the channel or one additional item which is currently being consumed.

[NB: I think that this could be fixed by introducing yet another lock. But it's
probably not worth it because it will just mean that as soon 'getCountChan' turns its
back on the channel, the item will still have disappeared.]

> > [although I consider
> >    mapM_ (uncurry putMVar) (zip counts (map (+1) vs))
> >  rather neat :)]
> 
> Not as neat as
>   zipWithM_ putMVar counts (map (+1) vs)

Point taken.

Volker
-- 
Volker Stolz * http://www-i2.informatik.rwth-aachen.de/stolz/ * PGP * S/MIME