开发者

Starting and Stopping Ruby Threads

开发者 https://www.devze.com 2022-12-14 12:48 出处:网络
How would I Start and stop a separate thread from within another thread? loop_a_stopped = true loop_a = Thread.new do

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
en开发者_运维百科d

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消