Ruby: Wait until all threads are completed using join and ThreadsWait.all_waits - what's the difference?

Consider the following example:

threads = []

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

Then there are two ways to wait for it to be done:

  1. Connection Usage:

    threads.each(&:join)
    
  2. Usage ThreadsWait:

    ThreadsWait.all_waits(threads)
    

Is there a difference between the two?

I know the class ThreadsWaithas other useful methods. And especially the question of the method all_waits.

+4
source share
1 answer

The documentation clearly states what all_waitsany transferred block will execute after each thread execution; joindoesn't offer anything like that.

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.

To do the same with join, I assume that you will need to do this:

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 )
+5

Source: https://habr.com/ru/post/1589458/


All Articles