加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby暂停线程

发布时间:2020-12-17 03:15:11 所属栏目:百科 来源:网络整理
导读:在 ruby中,是否可能导致线程从另一个并发运行的线程暂停. 下面是我到目前为止编写的代码.我希望用户能够输入’pause thread’和sample500线程来暂停. #!/usr/bin/env ruby# Creates a new thread executes the block every intervalSec for durationSec.def
在 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 threadn"
        sample500 = Thread
        beginTime = Time.now
        DoEvery(sample500,0.5,30) {File.open('abc','a') {|file| file.write("an")}}
    when "pause threadn"
        sample500.stop
    when "resume thread"
        sample500.run
    when "exitn"
        exit = TRUE
    end
end

解决方法

将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 threadn"
        sample500 = DoEvery(0.5,'a') {|file| file.write("an")} }
    when "pause threadn"
        sample500["stop"] = true
    when "resume threadn"
        sample500.run
    when "exitn"
        exit = TRUE
    end
end

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读