一个异步事件,它阻塞直到计数为零

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

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
JavaPax考试:从非标准Maven存储库解析Karaf特性存储库(XML文件)   java Spring启动Bean创建异常   java中将ArrayList转换为数组的方法   Android Studio的java Unity插件。   java在CheckStyle中从方法计数中排除getter和setter   HibernateJava。sql。SQLSyntaxErrorException:表/视图“序列”不存在   与命令行程序Java vs C通信   java WebView膨胀异常   java在O(n)java8流中寻找两个列表的交集   java使用Gradle运行单元测试时,最大堆大小在哪里设置?   ssl加载java应用程序(CXF)内的jks文件   CI:Jenkins Git:Simple Java项目:希望在特定时间在脚本上发送消息   java根据位置更改数字   java按数值排序字符串数组   macos java版本“1.6.0_65”是否与java 6模棱两可?   Cassandra中的java时间戳