【发布时间】:2021-11-14 00:31:40
【问题描述】:
我正在尝试使用 python 的 asyncio 模块构建一个应用程序,该模块可扩展并使用基于 asyncio 的其他模块,其想法是随着应用程序的增长轻松添加任务,利用同步原语在任务之间共享资源,然而我不知道哪种设计最适合我的意图。
import asyncio
async def task1():
while True:
# Code from task1
await asyncio.sleep(1)
async def task2():
while True:
# Code from task2
await asyncio.sleep(1)
async def task3():
while True:
# Code from task3
await asyncio.sleep(1)
async def main():
await asyncio.gather(
task1(),
task2(),
task3()
)
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
在上述方法中,每个任务都是一个while循环,在每次执行结束时产生,
import asyncio
async def task1():
# Code from task1
await asyncio.sleep(1)
async def task2():
# Code from task2
await asyncio.sleep(1)
async def task3():
# Code from task3
await asyncio.sleep(1)
async def main():
while True:
await asyncio.gather(
task1(),
task2(),
task3()
)
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
在最后一种方法中,gather 方法位于 while 循环中。
我也可能没有必要这样做,因为异步任务是以协作方式运行的,我会通过依次等待每个协程得到相同的结果,从而节省互斥锁的使用。
【问题讨论】:
标签: python concurrency operating-system python-asyncio mutex