请考虑以下示例:
threads = []
(0..10).each do |_|
threads << Thread.new do
# do async staff there
sleep Random.rand(10)
end
end
当它完成时,有两种方法可以等待:
ThreadsWait
:
ThreadsWait.all_waits(线程)这两种方法有什么区别吗?
我知道ThreadsWait
类还有其他有用的方法。特别是关于all_waits
方法的问题。
发布于 2015-05-22 16:56:11
文档清楚地指出,all_waits
将在每个线程执行之后执行任何经过的块;join
不提供类似的任何内容。
require "thwait"
threads = [Thread.new { 1 }, Thread.new { 2 }]
ThreadsWait.all_waits(threads) do |t|
puts "#{t} complete."
end # will return nil
# output:
# #<Thread:0x00000002773268> complete.
# #<Thread:0x00000002772ea8> complete.
为了在join
中实现同样的目标,我想您必须这样做:
threads.each do |t|
t.join
puts "#{t} complete."
end # will return threads
除此之外,all_waits
方法最终调用join_nowait
方法,该方法通过调用线程上的join
来处理每个线程。
如果没有任何块,我可以想象直接使用join
会更快,因为您会减少所有的ThreadsWait
方法。所以我试了一试:
require "thwait"
require "benchmark"
loops = 100_000
Benchmark.bm do |x|
x.report do
loops.times do
threads = [Thread.new { 2 * 1000 }, Thread.new { 4 * 2000 }]
threads.each(&:join)
end
end
x.report do
loops.times do
threads = [Thread.new { 2 * 1000 }, Thread.new { 4 * 2000 }]
ThreadsWait.all_waits(threads)
end
end
end
# results:
# user system total real
# 4.030000 5.750000 9.780000 ( 5.929623 )
# 12.810000 17.060000 29.870000 ( 17.807242 )
发布于 2021-07-09 09:14:04
使用map而不是每个映射,将等待它们,因为它需要它们的值来构建映射。
(0..10).map do |_|
Thread.new do
# do async staff there
sleep Random.rand(10)
end
end.map(&:join).map(&:value)
https://stackoverflow.com/questions/30400319
复制相似问题