简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM