[Haskell-cafe] Re: Waiting for thread to finish

Brad Clow brad at bjclow.org
Tue Nov 27 19:34:04 EST 2007

If you would like to wait on multiple threads, you can use STM like so:

import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception

main = do
  tc <- atomically $ newTVar 2
  run tc (print (last [1..100000000]))
  run tc (print (last [1..110000000]))
  print "Waiting...."
  atomically $ readTVar tc >>= \x -> if x == 0 then return () else retry
  print "OK."
    run tc f = forkIO (f `finally` atomReplace (\x -> x - 1) tc)

atomReplace fn x = atomically $ readTVar x >>= writeTVar x . fn


Recycle is good: Reuse is better

More information about the Haskell-Cafe mailing list