加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:等待使用join和ThreadsWait.all_waits完成的所有线程 –

发布时间:2020-12-17 02:55:24 所属栏目:百科 来源:网络整理
导读:请考虑以下示例: threads = [](0..10).each do |_| threads Thread.new do # do async staff there sleep Random.rand(10) endend 然后有2种方法可以在完成时等待: 使用join: threads.each(:join) 使用ThreadsWait: ThreadsWait.all_waits(threads) 这两
请考虑以下示例:

threads = []

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

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

>使用join:

threads.each(&:join)

>使用ThreadsWait:

ThreadsWait.all_waits(threads)

这两种方式之间有什么区别吗?

我知道ThreadsWait类有其他有用的方法.
并特别询问all_waits方法.

解决方法

documentation明确指出all_waits将在每个线程执行后执行任何传递的块;加入不提供这样的东西.

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.

为了实现同样的加入,我想你必须这样做:

threads.each do |t|
  t.join
  puts "#{t} complete."
end # will return threads

除此之外,all_waits方法最终调用join_nowait方法,该方法通过调用连接来处理每个线程.

没有任何阻塞,我会想象直接使用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.
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.
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.0 29.870000 ( 17.807242 )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读