Ruby Thread#kill and ensure blocks

Here's something interesting in Ruby: If a thread is killed and the portion of code that was running has a corresponding ensure block, that block will be executed before the thread is killed. This is nice in that the utility of ensure is maintained (IO objects will be closed, etc.), but it's perhaps unintuitive that the semantics of Thread.kill would allow for that. I suppose it's like command line kill and not kill -9.

t = Thread.start{
  begin
    puts "starting executing code!"
    sleep 1
    puts "done executing code!" # we don't expect to reach here
  rescue Exception
    puts "rescuing!"            # we don't expect to reach here
  ensure
    puts "ensuring!"            # will we reach here????? (yes)
  end
}
t.kill
t.join
puts "done!"
   ruby ../thing.rb
    ensuring!
    done!

John BachirCo-Founder and CTO of Medstro

comments powered by Disqus