gpt4 book ai didi

haskell - Haskell 的 Control.Concurrent.Async.mapConcurrently 可以有限制吗?

转载 作者:行者123 更新时间:2023-12-04 00:07:40 25 4
gpt4 key购买 nike

我试图在 Haskell 中并行运行多个下载,我通常只使用 Control.Concurrent.Async.mapConcurrently 函数。但是,这样做会打开大约 3000 个连接,这会导致 Web 服务器拒绝所有连接。是否可以完成与 mapConcurrently 相同的任务,但一次只能打开有限数量的连接(即一次只能打开 2 个或 4 个)?

最佳答案

一个快速的解决方案是使用 semaphore限制并发操作的数量。这不是最佳的(所有线程都是一次创建然后等待),但是可以:

import Control.Concurrent.MSem
import Control.Concurrent.Async
import Control.Concurrent (threadDelay)
import qualified Data.Traversable as T

mapPool :: T.Traversable t => Int -> (a -> IO b) -> t a -> IO (t b)
mapPool max f xs = do
sem <- new max
mapConcurrently (with sem . f) xs

-- A little test:
main = mapPool 10 (\x -> threadDelay 1000000 >> print x) [1..100]

关于haskell - Haskell 的 Control.Concurrent.Async.mapConcurrently 可以有限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18896103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com