如何让定时器中断正在等待的进程?

发布于 2024-12-27 17:09:49 字数 438 浏览 3 评论 0原文

我正在尝试在使用标准读取-评估-打印循环的程序中实现警报。

代码示例如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑脸一如从前 2025-01-03 17:09:49

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文