Friday, September 30, 2022

[FIXED] How can I run a list of independent IO actions in parallel?

Issue

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.


Solution

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.



Answered By - K. A. Buhr
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.