Skip to content

Instantly share code, notes, and snippets.

@sordina
Created February 4, 2011 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sordina/810920 to your computer and use it in GitHub Desktop.
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.
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