I just ran across an issue that probably exposes my ignorance of common threading semantics. I assumed that the following ruby was valid:
d = Thread.new{ Thread.stop }
d.join
That is, I thought that joining a stopped thread would simply be a NOP – the thread is already finished, so join should return immediately.
Instead, Ruby-1.8.6 (irb) on Mac returns the following:
deadlock 0x569f14: sleep:- - (irb):1
deadlock 0x35700: sleep:J(0x569f14) (main) - (irb):2
fatal: Thread(0x35700): deadlock
from (irb):2:in `join'
from (irb):2
Can anyone briefly explain why this is so? Is this just an implementation issue or a higher-level semantic that has gone over my head?
Your code creates a new
Threadobject with the corresponding block but never runs it, so when you do thejoin, you’re waiting for a thread to complete that is never started. Start the thread before you do the join and it should be fine: