Skip to content

Instantly share code, notes, and snippets.

@nicolasff
Created January 13, 2009 12:12
Show Gist options
  • Save nicolasff/46421 to your computer and use it in GitHub Desktop.
Save nicolasff/46421 to your computer and use it in GitHub Desktop.
module Main where
import Control.Concurrent
import Control.Exception
import System.IO.Unsafe
proc :: MVar Int -> IO ()
proc m = do
v <- takeMVar m
putMVar m (v+1)
return ()
children :: MVar [MVar ()]
children = unsafePerformIO (newMVar [])
waitForChildren :: IO ()
waitForChildren = do
cs <- takeMVar children
case cs of
[] -> return ()
m:ms -> do
putMVar children ms
takeMVar m
waitForChildren
forkChild :: IO () -> IO ThreadId
forkChild io = do
mvar <- newEmptyMVar
childs <- takeMVar children
putMVar children (mvar:childs)
forkIO (io `finally` putMVar mvar ())
runChildren _ 0 = return ()
runChildren m n = do
forkChild (proc m)
runChildren m (n-1)
main = do
m <- newEmptyMVar
putMVar m 0
runChildren m 1000000
waitForChildren
v <- takeMVar m
putStrLn ("total = " ++ show v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment