Python: Pass or Sleep for long running processes?

前端 未结 7 1413
情书的邮戳
情书的邮戳 2020-11-30 05:10

I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the applica

7条回答
  •  误落风尘
    2020-11-30 05:49

    If you are looking for a short, zero-cpu way to loop forever until a KeyboardInterrupt, you can use:

    from threading import Event
    
    Event().wait()
    

    Note: Due to a bug, this only works on Python 3.2+. In addition, it appears to not work on Windows. For this reason, while True: sleep(1) might be the better option.

    For some background, Event objects are normally used for waiting for long running processes to complete:

    def do_task():
        sleep(10)
        print('Task complete.')
        event.set()
    
    event = Event()
    Thread(do_task).start()
    event.wait()
    
    print('Continuing...')
    

    Which prints:

    Task complete.
    Continuing...
    

提交回复
热议问题