The version of your example is fixed here:
STDOUT.sync = true loop_a_stopped = true loop_a = Thread.new do loop do Thread.stop if loop_a_stopped # Do stuff sleep(1) end end loop_b = Thread.new do loop do print "> " response = gets case response.strip.downcase when "start" loop_a_stopped = false loop_a.wakeup when "stop" loop_a_stopped = true when "exit" # Terminate thread A regardless of state loop_a.terminate! # Terminate this thread Thread.exit end end end loop_b.join loop_a.join
Managing threads can be a bit complicated. Stopping the thread does not end it, just removes it from the scheduler, so you really need to kill it when Thread # finishes! before it is really finished.
tadman
source share