等待状态更改(变量更改)超时的有效方法?
我确信这有点常见,所以我很好奇在 Python 中执行此操作的可接受/有效的方法是什么。
简而言之,我只是忙着等待变量更新。同时我需要一个超时方案,但我觉得必须有更好的方法来做到这一点。
目前我正在做这样的事情:
wait_start = time.time()
while state != NEW_STATE:
if time.time() - wait_start > timeout:
print "Timed out!"
# Do something
# Continuing on...
我显然无法入睡,因为我需要知道状态何时发生变化。
那么,实现状态(变量)更改超时的有效方法是什么?
I'm sure this is somewhat common, so I am curious what are the accepted/efficient ways of doing this in Python.
Put simply, I am just busy-waiting for a variable to be updated. At the same time I need a timeout scheme, but I feel there must be a better way of doing this.
Currently I do something like this:
wait_start = time.time()
while state != NEW_STATE:
if time.time() - wait_start > timeout:
print "Timed out!"
# Do something
# Continuing on...
I obviously just can't sleep, because I need to know when the state has changed.
So what is an efficient method of implementing a timeout for a state (variable) change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
条件变量 和 事件通常用于此类事情。两者都需要改变变量的一方的合作。
Condition variables and events are often used for this type of thing. Both require cooperation from the side that's changing the variable.