调用Thread.join阻止当前(主)线程.但是当主线程退出时,不会在所有产生的线程中调用join结果,以被杀死.一个如何在Ruby中生成持久的子句线程而不阻塞主线程?
这是连接的典型用法.
- 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
但我正在寻找如何获得这个
- Creating thread 1
- Creating thread 2
- ...
- 101 threads
- Thread 1 done
- Thread 2 done
- ...
解决方法
您只需将线程累积到另一个容器中,然后在创建完毕后逐个加入它们:
- 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变量,因为我不断被覆盖,并且您的输出将是100行“线程100完成”;相反,你必须将它绑定到我的一个副本,我巧妙地命名为j.