使用Signal中断Ruby线程

时间:2017-03-13 13:56:20

标签: ruby multithreading signals

我在主线程和工作线程之间拆分了一个程序。我想调用一个中断所有内容的软件中断,但它似乎只会中断主线程。

简化的概念证明如下。我定义了一个陷阱,并让另一个线程调用Process.kill来创建中断。

Signal.trap("INT") do 
  Thread.new {
    puts "int 1"
    sleep 5
    puts "int 2"
    sleep 5
  }.join
end

int_thread = Thread.new {
  Process.kill("INT", Process.pid)
}

work_thread = Thread.new {
  puts "work 1"
  sleep 5
  puts "work 2"
  sleep 5  
  puts "work 3"
  sleep 5
}

puts "main 1"
sleep 5
puts "main 2"
sleep 5
puts "main 3"
sleep 5

=>

main 1
work 1
int 1 # interrupt called here
work 2 # worker thread still running
int 2
work 3
main 2 # main thread continues after interrupt
main 3

为什么工作线程不受中断影响?有什么我做错了吗?有什么办法可以为工作线程调用中断吗?

0 个答案:

没有答案