Python - wait on a condition without high cpu usage

后端 未结 3 1411
我在风中等你
我在风中等你 2021-01-16 05:22

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         


        
3条回答
  •  攒了一身酷
    2021-01-16 06:12

    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)

提交回复
热议问题