gpt4 book ai didi

ruby - 限制要执行的线程数

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

我试图限制必须同时执行的线程数量,或者将数组的元素分开一定数量并单独发送(拼接),但我不知道从哪里以及如何开始。代码正在快速执行线程,这阻碍了很多。

我的代码:

file = File.open('lista.txt').read
file.gsub!(/\r\n?/, "")
arr = []

file.each_line do |log|
arr << Thread.new{

puts login = Utils.req("GET","http://httpbin.org/GET",{
'Host': 'api.httpbin.org',
'content-type': 'application/json',
'accept': '*/*',
},
false)
}
end

arr.each(&:join)

最佳答案

如果要限制并发运行的线程数,请使用线程池。这将创建一个工作线程“池”并限制同时运行的线程数量。您可以编写自己的,或使用像 celluloid 这样的 gem .

class Whatever
include Celluloid

def login_request
Utils.req(
"POST",
"http://httpbin.org/post",
{
'Host': 'api.httpbin.org',
'content-type': 'application/json',
'accept': '*/*',
},
false
)
end
end

# Only 5 threads will run at a time.
pool = Whatever.pool(size: 5)

file.each_line do |log|
split = log.split("|")
id = split[0]
number = split[1]

# If there's a free working in the pool, this will execute immediately.
# If not, it will wait until there is a free worker.
pool.login_request
end

关于ruby - 限制要执行的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64273683/

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