Ruby join阻塞主线程

Ruby join阻塞主线程,ruby,multithreading,Ruby,Multithreading,调用Thread.join会阻止当前(主)线程。但是,不调用join会导致在主线程退出时杀死所有生成的线程。如何在Ruby中生成持久子线程而不阻塞主线程 下面是join的一个典型用法 for i in 1..100 do puts "Creating thread #{i}" t = Thread.new(i) do |j| sleep 1 puts "Thread #{j} done" end t.join end puts "#{Thread.list.siz

调用Thread.join会阻止当前(主)线程。但是,不调用join会导致在主线程退出时杀死所有生成的线程。如何在Ruby中生成持久子线程而不阻塞主线程

下面是join的一个典型用法

for i in 1..100 do
  puts "Creating thread #{i}"
  t = Thread.new(i) do |j|
    sleep 1
    puts "Thread #{j} done"
  end
  t.join
end
puts "#{Thread.list.size} threads"
这给

Creating thread 1 Thread 1 done Creating thread 2 Thread 2 done ... 1 threads 创建线程1 线程1已完成 创建线程2 线程2已完成 ... 1线程 但我在寻找如何得到这个

Creating thread 1 Creating thread 2 ... 101 threads Thread 1 done Thread 2 done ... 创建线程1 创建线程2 ... 101线 线程1已完成 线程2已完成 ...
代码在Ruby 1.8.7和1.9.2中都给出了相同的输出,您需要在循环之外加入线程

for i in 1..100 do
  puts "Creating thread #{i}"
  t = Thread.new(i) do |mi|
    sleep 1
    puts "Thread #{mi} done"
  end
end

# Wait for all threads to end
Thread.list.each do |t|
  # Wait for the thread to finish if it isn't this thread (i.e. the main thread).
  t.join if t != Thread.current
 end

您只需将线程累积到另一个容器中,然后在创建完所有线程后,将其逐个加入:

my_threads = []
for i in 1..100 do
    puts "Creating thread #{i}"
    my_threads << Thread.new(i) do |j|
        sleep 1
        puts "Thread #{j} done"
    end
end
puts "#{Thread.list.size} threads"

my_threads.each do |t|
    t.join
end
myu线程=[]
因为我在1..100做
放置“创建线程#{i}”

是的,这很有效。我原以为Ruby可以隐式地处理这个问题,而不必跟踪线程并在最后执行连接调用。是的,我不应该在每个线程中使用全局I。基本的东西。谢谢你干净的修理。我将更新代码。在Ruby 1.9中,块参数始终是本地的,因此不需要重命名变量。不过你会得到警告的。(变量
i
shadows外部变量或类似的东西。)