Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting and Stopping Ruby Threads

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
like image 208
RyanScottLewis Avatar asked Dec 22 '09 20:12

RyanScottLewis


1 Answers

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.

like image 70
tadman Avatar answered Sep 20 '22 18:09

tadman