简体   繁体   中英

Python - wait on a condition without high cpu usage

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

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?

See Busy_loop#Busy-waiting_alternatives :

Most operating systems and threading libraries provide a variety of system calls that will block the process on an event, such as lock acquisition, timer changes, I/O availability or signals.

Basically, to wait for something, you have two options (same as IRL):

  • Check for it periodically with a reasonable interval (this is called "polling")
  • Make the event you're waiting for notify you: invoke (or, as a special case, unblock) your code somehow (this is called "event handling" or "notifications". For system calls that block, "blocking call" or "synchronous call" or call-specific terms are typically used instead)

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

This is not really a Python problem. Optimally, you want to put your process to sleep and wait for some sort of signal that the action has occured, which will use no CPU while waiting. So it's not so much a case of writing Python code but figuring out what mechanism is used to make condition true and thus wait on that.

If the condition is a simple flag set by another thread in your program rather than an external resource, you need to go back and learn from scratch how threading works.

Only if the thing that you're waiting for does not provide any sort of push notification that you can wait on should you consider polling it in a loop. A sleep will help reduce the CPU load but not eliminate it and it will also increase the response latency as the sleep has to complete before you can commence processing.

As for waiting on events, an event-driven paradigm might be what you want unless your program is utterly trivial. Python has the Twisted framework for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM