启动和停止Ruby线程

如何在另一个线程中启动和停止单独的线程?

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
这是您的示例的修复版本:

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#terminate来终止它!在它真正完成之前.

本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院