views:

100

answers:

1

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
+3  A: 

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.

tadman
Ahh, this makes alot more sense, thank you. Although, I was wondering what the first like, `STDOUT.sync = true` was for. I'll figure it out though.
c00lryguy
Hm, it seems the `gets` method stops loop_a from running. Whats up with this?
c00lryguy
There seems to be no problem with the code above. I can run this without problem. I suspect what you did in loop_a (the # Do stuff) might halt loop_a.
bryantsai
What I did in loop_a is it loads a page in Watir. The only way it works is if I hold down the Enter key causing the console to scroll.. If I don't hold down enter, loop_a will not run it's code.
c00lryguy
I'm using Ruby 1.8.6, by the way. Thats the only version of Ruby that I could get Watir running in.
c00lryguy