Created
January 13, 2009 12:12
-
-
Save nicolasff/46421 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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