Python threading: can I sleep on two threading.Event()s simultaneously?

前端 未结 8 1641
悲&欢浪女
悲&欢浪女 2020-12-09 03:35

If I have two threading.Event() objects, and wish to sleep until either one of them is set, is there an efficient way to do that in python? Clearly I could do

8条回答
  •  再見小時候
    2020-12-09 04:03

    def wait_for_event_timeout(*events):
        while not all([e.isSet() for e in events]):
            #Check to see if the event is set. Timeout 1 sec.
            ev_wait_bool=[e.wait(1) for e in events]
            # Process if all events are set. Change all to any to process if any event set
            if all(ev_wait_bool):
                logging.debug('processing event')
            else:
                logging.debug('doing other work')
    
    
    e1 = threading.Event()
    e2 = threading.Event()
    
    t3 = threading.Thread(name='non-block-multi',
                          target=wait_for_event_timeout,
                          args=(e1,e2))
    t3.start()
    
    logging.debug('Waiting before calling Event.set()')
    time.sleep(5)
    e1.set()
    time.sleep(10)
    e2.set()
    logging.debug('Event is set')
    

提交回复
热议问题