Ruby:使用join和ThreadsWait等待所有线程完成。all_等待-有什么区别?
考虑以下示例:Ruby:使用join和ThreadsWait等待所有线程完成。all_等待-有什么区别?,ruby,multithreading,thread-safety,Ruby,Multithreading,Thread Safety,考虑以下示例: threads = [] (0..10).each do |_| threads << Thread.new do # do async staff there sleep Random.rand(10) end end 使用ThreadsWait: ThreadsWait.all_waits(threads) 这两种方法有什么区别吗 我知道ThreadsWait类还有其他有用的方法。 并特别询问all_waits方法。明确说明all
threads = []
(0..10).each do |_|
threads << Thread.new do
# do async staff there
sleep Random.rand(10)
end
end
ThreadsWait
:
ThreadsWait.all_waits(threads)
ThreadsWait
类还有其他有用的方法。
并特别询问all_waits
方法。明确说明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.
除此之外,all_wait
方法最终调用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 )
threads.each do |t|
t.join
puts "#{t} complete."
end # will return threads
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 )