Ruby暂停线程

Jea*_*Luc 5 ruby multithreading thread-safety

在ruby中,是否可能导致线程从另一个并发运行的线程暂停.

下面是我到目前为止编写的代码.我希望用户能够输入'pause thread'和sample500线程来暂停.

#!/usr/bin/env ruby

# Creates a new thread executes the block every intervalSec for durationSec.
def DoEvery(thread, intervalSec, durationSec)
    thread = Thread.new do
        start = Time.now

        timeTakenToComplete = 0
        loopCounter = 0
        while(timeTakenToComplete < durationSec && loopCounter += 1)

            yield

            finish = Time.now

            timeTakenToComplete = finish - start

            sleep(intervalSec*loopCounter - timeTakenToComplete)    
        end
    end
end

# User input loop.
exit = nil
while(!exit)
    userInput = gets
    case userInput
    when "start thread\n"
        sample500 = Thread
        beginTime = Time.now
        DoEvery(sample500, 0.5, 30) {File.open('abc', 'a') {|file| file.write("a\n")}}
    when "pause thread\n"
        sample500.stop
    when "resume thread"
        sample500.run
    when "exit\n"
        exit = TRUE
    end
end
Run Code Online (Sandbox Code Playgroud)

Dfr*_*Dfr 3

将 Thread 对象作为参数传递给DoEvery函数是没有意义的,因为您立即用 Thread.new 覆盖它,查看这个修改后的版本:

def DoEvery(intervalSec, durationSec)
    thread = Thread.new do
        start = Time.now
        Thread.current["stop"] = false

        timeTakenToComplete = 0
        loopCounter = 0
        while(timeTakenToComplete < durationSec && loopCounter += 1)
            if Thread.current["stop"]
              Thread.current["stop"] = false
              puts "paused"
              Thread.stop
            end

            yield

            finish = Time.now

            timeTakenToComplete = finish - start

            sleep(intervalSec*loopCounter - timeTakenToComplete)

        end
    end
    thread
end

# User input loop.
exit = nil
while(!exit)
    userInput = gets
    case userInput
    when "start thread\n"
        sample500 = DoEvery(0.5, 30) {File.open('abc', 'a') {|file| file.write("a\n")} }
    when "pause thread\n"
        sample500["stop"] = true
    when "resume thread\n"
        sample500.run
    when "exit\n"
        exit = TRUE
    end
end
Run Code Online (Sandbox Code Playgroud)

这里DoEvery返回新的线程对象。另请注意,Thread.stop 在正在运行的线程内部调用,您不能直接从另一个线程停止一个线程,因为它不安全。