views:

46

answers:

2

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!

+3  A: 

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
Jean
+1  A: 

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,

Paul Leader