某种 Ruby“中断”
这就是我正在做的——我有一个 ruby 脚本,每分钟打印出信息。我还为陷阱设置了一个过程,以便当用户按下 ctrl-c 时,进程就会中止。代码看起来像这样:
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
现在代码本身是有效的并且运行良好,但是它做了很多无用的工作,尽可能频繁地检查 switch
的值。它会尽可能多地使用处理器(至少 100% 地使用一个核心),因此非常浪费。我怎样才能做类似的事情,其中事件经常更新,而不浪费大量的周期?
感谢所有帮助并提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有几种解决方案。例如,如果您期望有很多信号并希望将每个信号作为一个事件进行处理,则可以使用 Thread::Queue。如果您真的只是等待 ^C 发生,而没有与其他线程进行复杂的交互,我认为使用 Thread#wakeup 可能很简单:
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:
如果您只是捕获 ctrl-c 中断并且不介意在按下按键和中断之间短暂等待...
“睡眠”功能使用系统计时器,因此在等待时不会耗尽 CPU。如果您想要更精细的计时分辨率,只需将 sleep 1 替换为 sleep 0.5 或更小,以减少检查之间的时间,
If you are just trapping ctrl-c interrupts and don't mind a short wait between pressing the keys and it breaking out then...
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,