如何让定时器中断正在等待的进程?
我正在尝试在使用标准读取-评估-打印循环的程序中实现警报。
代码示例如下:
while True:
input = get_input() # A function that waits for input and
# returns the input once it is obtained
set_alarm(interpret(input)) # A function that sets the alarm
Set_alarm 使用 threading.Timer 类。不过,这有一个问题。计时器按时激活,但当 get_input() 等待输入时,计时器将等待该过程完成,然后再生成所需的输出。
有没有办法让定时器的回调函数在激活后立即中断等待函数并产生输出?
谢谢!
I am trying to implement alarms in a program that uses a standard read-eval-print loop.
An example of the code would be something like this:
while True:
input = get_input() # A function that waits for input and
# returns the input once it is obtained
set_alarm(interpret(input)) # A function that sets the alarm
Set_alarm uses the threading.Timer class. There is one problem with this, though. The timer activates on time, but when get_input() is waiting for an input, the timer will wait for that process to complete before producing the required output.
Is there a way for the callback function of the timer to interrupt the waiting function and produce the output immediately after it is activated?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CPython 检查各个纯 Python 步骤之间的信号。 get_input() 很可能拥有全局解释器锁,并且信号处理将被延迟,直到 get_input 返回。
解决方案是使用非阻塞调用以尊重超时的方式征求用户输入。根据您的平台,您可能可以使用 kbhit 或选择 (使用 stdin)来获取用户输入。
CPython checks for signals between individual pure Python steps. It is likely that get_input() owns the global interpreter lock and that signal processing will be delayed until get_input returns.
The solution is to use non-blocking calls to solicit user input in a way that respects timeouts. Depending on your platform, you may be able to use kbhit or select (with stdin) to get the user input.