Ruby:等待使用join和ThreadsWait.all_waits完成的所有线程 – 有什么区别?

请考虑以下示例:

threads = [] (0..10).each do |_| threads << Thread.new do #do async staff there sleep Random.rand(10) end end 

然后有2种方法可以在完成后等待:

  1. 使用join:

threads.each(&:join)

  1. 使用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: # # complete. # # 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 )