一个异步事件,它阻塞直到计数为零
countdown-event的Python项目详细描述
倒计时事件
当计数不为零时阻塞的同步类。
下面是一个示例
importasynciofromcountdown_eventimportCountdownEventasyncdeflong_running_task(countdown_event,cancellation_event):count=countdown_event.increment()print(f'incremented count to {count}')try:print('Waiting for cancellation event')awaitcancellation_event.wait()finally:count=countdown_event.decrement()print(f'decremented count to {count}')asyncdefstop_tasks(secs,countdown_event,cancellation_event):print(f'waiting {secs} seconds before setting the cancellation event')awaitasyncio.sleep(secs)print('setting the cancellation event')cancellation_event.set()print('waiting for tasks to finish')awaitcountdown_event.wait()print('countdown event cleared')asyncdefmain_async():cancellation_event=asyncio.Event()countdown_event=CountdownEvent()tasks=[long_running_task(countdown_event,cancellation_event),long_running_task(countdown_event,cancellation_event),long_running_task(countdown_event,cancellation_event),stop_tasks(5,countdown_event,cancellation_event)]awaitasyncio.wait(tasks)assertcountdown_event.count==0print("done")if__name__=="__main__":asyncio.run(main_async())
这是输出。
incremented count to 1
Waiting for cancellation event
incremented count to 2
Waiting for cancellation event
waiting 5 seconds before setting the cancellation event
incremented count to 3
Waiting for cancellation event
setting the cancellation event
waiting for tasks to finish
decremented count to 2
decremented count to 1
decremented count to 0
countdown event cleared
done