Python-等待条件下CPU使用率不高 [英] Python - wait on a condition without high cpu usage

查看:395
本文介绍了Python-等待条件下CPU使用率不高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,说我想等待某种情况发生,这种情况可能会在任意随机时间发生。

In this case, say I wanted to wait on a condition to happen, that may happen at any random time.

 while True:
    if condition:
        #Do Whatever
    else:
        pass

如您所见,通过只会发生,直到条件为True。但是,当条件不是True时,CPU被钉住会导致更高的CPU使用率的传递,而我只是希望它等待直到条件发生。我该怎么办?

As you can see, pass will just happen until the condition is True. But while the condition isn't True the cpu is being pegged with pass causing higher cpu usage, when I simply just want it to wait until the condition occurs. How may I do this?

推荐答案

如前所述,您可以a)轮询即检查条件,如果条件不正确等待一段时间,如果您的情况是外部事件,则可以安排阻塞状态以等待状态更改,或者还可以查看发布订阅模型 pubsub ,其中您的代码注册了对给定项目的兴趣,然后代码的其他部分发布了该项目。

As already mentioned you can a) poll i.e. check for a condition and if it is not true wait for some time interval, if your condition is an external event you can arrange for a blocking wait for the state to change, or you can also take a look at the publish subscribe model, pubsub, where your code registers an interest in a given item and then other parts of the code publish the item.

这篇关于Python-等待条件下CPU使用率不高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆