Some kind of ruby ​​"Interruption"

So here is what I do - I have a ruby ​​script that prints information every minute. I also created proc for the trap, so when the user press 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 works well, but it does a lot of useless work, checking the value switchas often as possible. It uses as many processors as it can get (at least 100% of one core), so it’s pretty wasteful. How can I do something like this where an event is updated so often without spending tons of cycles?

All help is appreciated and thanks in advance!

+3
2

ctrl-c , ...

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

"sleep" , . , sleep 1 sleep 0.5 , ,

+4

. - Thread:: Queue, , . , ^ C , , Thread # wakeup:

c = Thread.current

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

while true
  sleep
  puts "wake"
end
+6

Source: https://habr.com/ru/post/1770251/


All Articles