Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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
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