Starting and stopping Ruby Threads

How would I start and stop a single thread from another thread?

loop_a_stopped = true loop_a = Thread.new do loop do Thread.stop if loop_a_stopped # Do stuff sleep 3 end end loop_b = Thread.new do loop do response = ask("> ") case response.strip.downcase when "start" loop_a_stopped = false loop_a.run when "stop" loop_a_stopped = true when "exit" break end end end loop_a.join loop_b.join 
+6
multithreading ruby
source share
1 answer

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.

+8
source share

All Articles