简体   繁体   English

如何并行运行独立的 IO 操作列表?

[英]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?是否有与sequenceA[IO a]做同样的事情,但同时运行它们的东西? I don't need any fancy concurrency stuff like locking since all IO actions are independent.我不需要任何花哨的并发东西,比如锁定,因为所有 IO 操作都是独立的。

The async package works well for this. async package 对此非常有效。 As mentioned in a comment, mapConcurrently from that package will run a list of IO actions in parallel.如评论中所述, mapConcurrently从 package 将并行运行 IO 操作列表。 In particular, specialized to a list, the expression mapConcurrently id has the type you want:特别是,专门用于列表,表达式mapConcurrently id具有您想要的类型:

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.如果您不关心返回值,请改用mapConcurrently_ id

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.如果您实际上并不需要 IO 并且真的想并行运行一堆纯计算,那么parallel package 会更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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