gpt4 book ai didi

ruby - 有限制的 Ruby 线程

转载 作者:数据小太阳 更新时间:2023-10-29 07:14:03 24 4
gpt4 key购买 nike

我有一个任务需要执行,do_stuff(opts),每个任务需要大约 1 秒,即使其中 1 - 10 个是并行运行的。我需要在最后收集每个操作的结果数组。

如果我有 30 件事情要做,我将如何有效地使用线程来排队 do_stuff(opts) 操作,以便同时运行不超过 10 件,但没有给出结果数组/print/etc 直到完成所有 (30) 个任务?

我通常至少有一些代码来尝试说明我的意思,但是对于线程我有点不知所措!提前致谢

最佳答案

我不知道它对于更复杂的应用程序的效果如何,但我发现类似这样的东西非常适合使用 macruby 的简单线程场景。

thread_limit = 4

threads = []
things_to_process.each do |thing|
until threads.map { |t| t.status }.count("run") < thread_limit do sleep 5 end
threads << Thread.new { the_task(thing) }
end
output = threads.map { |t| t.value }

until 循环一直等待,直到运行的已创建线程少于指定数量,然后才允许主线程继续执行以启动下一个线程。

输出变量将被分配一个由 the_task 返回的值组成的数组,其顺序与输入数组 things_to_process 相对应。主线程将阻塞,直到每个创建的线程都返回一个值。

关于ruby - 有限制的 Ruby 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1697504/

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