启动和停止Ruby线程

前端之家收集整理的这篇文章主要介绍了启动和停止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来终止它!在它真正完成之前.

猜你在找的Ruby相关文章