public
Last active

Run a list of IO actions simultaneously, then wait for them all to finish, returning a list of their results.

  • Download Gist
Sewn Threads
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.