Thread.join阻塞主线程 [英] Thread.join blocks the main thread
问题描述
调用Thread.join会阻止当前(主)线程.但是,不调用join会导致在主线程退出时杀死所有产生的线程.如何在Ruby中生成持久子线程而不阻塞主线程?
Calling Thread.join blocks the current (main) thread. However not calling join results in all spawned threads to be killed when the main thread exits. How does one spawn persistent children threads in Ruby without blocking the main thread?
这是join的典型用法.
Here's a typical use of 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
但是我正在寻找如何获得这个
but I'm looking for how to get this
Creating thread 1
Creating thread 2
...
101 threads
Thread 1 done
Thread 2 done
...
代码在Ruby 1.8.7和1.9.2中提供相同的输出
The code gives the same output in both Ruby 1.8.7 and 1.9.2
推荐答案
您只需将线程堆积在另一个容器中,然后在创建完所有线程之后将它们逐个join
:
You simply accumulate the threads in another container, then join
them one-by-one after they've all been created:
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
您也不能将线程绑定到i
变量,因为i
会不断被覆盖,并且您的输出将是100行"Thread 100 done"(完成线程100);相反,您必须将其绑定到i
的副本,我巧妙地将其命名为j
.
You also can't bind the thread to the i
variable because i
gets constantly overwritten, and your output will be 100 lines of "Thread 100 done"; instead, you have to bind it to a copy of i
, which I have cleverly named j
.
这篇关于Thread.join阻塞主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!