Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)

Solution 2:

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.


Solution 3:

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.


Post a Comment for "Python - Wait On A Condition Without High Cpu Usage"