Created
February 4, 2011 09:35
-
-
Save sordina/810920 to your computer and use it in GitHub Desktop.
Run a list of IO actions simultaneously, then wait for them all to finish, returning a list of their results.
This file contains hidden or 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
import Control.Concurrent | |
import Random | |
main = print =<< threadAndJoin (replicate 10 randomAction) | |
randomAction = do | |
x <- randomRIO (0::Double,2) | |
threadDelay $ floor $ x * (10 ** 6) | |
print x >> return x | |
threadAndJoin :: [IO a] -> IO [a] | |
threadAndJoin = (>>= mapM takeMVar) . mapM bg | |
where | |
bg :: IO a -> IO (MVar a) | |
bg action = do | |
x <- newEmptyMVar | |
forkIO $ action >>= putMVar x | |
return x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment