gpt4 book ai didi

asynchronous - 在 F# 中,如何在没有可变集合的异步计算中创建 Async 列表?

转载 作者:行者123 更新时间:2023-12-05 02:25:58 26 4
gpt4 key购买 nike

我有一个使用 F# 中的生产者/消费者模式的小程序。我想启动 1 个生产者,然后启动 8 个消费者,等待生产者,然后等待消费者并结束程序。

启动它的代码是:

async {
let! p = Async.StartChild producer
let maxConcurrent = 8

let consumers = List<Async<unit>>()

for _ in 0 .. maxConcurrent - 1 do
let! c = Async.StartChild consumer
consumers.Add(c)

do! p

for i in 0 .. maxConcurrent - 1 do
do! consumers[i]

}
|> Async.RunSynchronously

虽然这行得通,但使用 System.Collections.Generic 中的可变列表而不是仅使用 F# 列表感觉不对。但是我无法使用 List 生成所需的异步列表。我试过:

let consumers2 = List.init 8 (fun _ -> async {
let! c = Async.StartChild consumer
return c
})

但这现在又将其包装在异步中,因此它变成了 list<async<async<unit>>> ,如果它改为返回!然后应用程序挂起(我猜是因为我不是在等待应该启动任务的任务,而是也在等待等待完成的任务)

Full code is available here

最佳答案

我认为 Async.Parallel 会按照您想要的方式扁平化异步。以下似乎对我来说工作正常:

async {
// I need the producer to run in it's own thread, not shared by the threadpool, because I rely on the consumer being allowed to block the thread with .Take
let! p = Async.StartChild producer

let maxConcurrent = 8
let! consumers =
List.init maxConcurrent (fun _ ->
Async.StartChild consumer)
|> Async.Parallel

do! p

for c in consumers do
do! c
}
|> Async.RunSynchronously

关于asynchronous - 在 F# 中,如何在没有可变集合的异步计算中创建 Async<unit> 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74131612/

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