Home > Net >  How can I run a list of independent IO actions in parallel?
How can I run a list of independent IO actions in parallel?

Time:09-04

Is there something that does the same thing as sequenceA does to [IO a], but that runs them concurrently? I don’t need any fancy concurrency stuff like locking since all IO actions are independent.

CodePudding user response:

The async package works well for this. As mentioned in a comment, mapConcurrently from that package will run a list of IO actions in parallel. In particular, specialized to a list, the expression mapConcurrently id has the type you want:

mapConcurrently id :: [IO a] -> IO [a]

so:

import Control.Concurrent.Async

main = mapConcurrently id [putStrLn "foo", putStrLn "bar"]

If you don't care about the return values, use mapConcurrently_ id instead.

If you don't actually need IO and are really tring to run a bunch of pure computations in parallel, then the parallel package would be more appropriate.

  • Related