Deadlock when using Control.Concurrent.Chan

Ben Franksen ben.franksen at
Sat Feb 28 09:14:01 EST 2009

This code demonstrates the problem:

import Control.Concurrent
import Control.Concurrent.Chan
import Control.Monad

test = do
  c <- newChan
  forkIO $ forever $ do
    i <- readChan c
    print i
  writeChan c 1
  threadDelay 1000000
  isEmptyChan c >>= print

Test session:

ben at sarun[1]: .../hca/current > ghci Bug5.hs
GHCi, version 6.10.1:  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( Bug5.hs, interpreted )
Ok, modules loaded: Main.
*Main> test

The program hangs here. This is a deadlock caused by the calls to
isEmptyChan and readChan both waiting on the same MVar, as a quick look at
the sources reveals. I don't have an immediate fix but is shouldn't be too
hard to find one. I can try to, if it is consensus that this is a bug.

Incidentally, if I replace Chan with TChan (and wrap all xxxTChan calls in
an atomically), then this code terminates just fine.


More information about the Libraries mailing list