Some sort of Ruby “Interrupt”

前提是你 提交于 2019-12-21 18:32:32

问题


So here's what I'm doing -- I have a ruby script that prints out information every minute. I've also set up a proc for a trap so that when the user hits ctrl-c, the process aborts. The code looks something like this:

switch = true

Signal.trap("SIGINT") do
    switch = false
end

lastTime = Time.now

while switch do
    if Time.now.min > lastTime.min then
        puts "A minute has gone by!"
    end
end

Now the code itself is valid and runs well, but it does a lot of useless work checking the value of switch as often as it can. It uses up as much of the processor as it can get (at least, 100% of one core), so it's pretty wasteful. How can I do something similar to this, where an event is updated every so often, without wasting tons of cycles?

All help is appreciated and thanks in advance!


回答1:


If you are just trapping ctrl-c interrupts and don't mind a short wait between pressing the keys and it breaking out then...

switch = true

Signal.trap("SIGINT") do
    switch = false
end

lastTime = Time.now

while switch do
    sleep 1
    if Time.now.min > lastTime.min then
        puts "A minute has gone by!"
    end
end

The 'sleep' function uses the system timers, so doesn't use up the CPU while waiting. If you want finer resolution timing just replace sleep 1 with sleep 0.5 or even smaller to reduce the time between checks,




回答2:


You have several solutions. One is to use a Thread::Queue if you expect many signals and want to process each of them as an event, for example. If you are really just waiting for ^C to happen with no complex interactions with other threads, I think it may be simple to use Thread#wakeup:

c = Thread.current

Signal.trap("SIGINT") do
  c.wakeup
end

while true
  sleep
  puts "wake"
end


来源:https://stackoverflow.com/questions/3966063/some-sort-of-ruby-interrupt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!