How would I Start and stop a separate thread from within 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
Here's a repaired version of your example:
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
Thread management can be a bit tricky. Stopping a thread doesn't terminate it, just removes it from the scheduler, so you actually need to kill it off with Thread#terminate! before it is truly finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With