python 协程
2021-05-30 22:05
标签:star time pre app __name__ 并行 end started for python 协程 标签:star time pre app __name__ 并行 end started for 原文地址:https://www.cnblogs.com/namejmj/p/14747488.htmlimport asyncio
import time
async def say_after(delay, what):
"""使用 async 声明函数"""
await asyncio.sleep(delay)
print(what)
async def main():
# 一个一个执行
print(f"started at {time.strftime(‘%X‘)}")
await say_after(1, ‘hello‘)
await say_after(2, ‘world‘)
print(f"started at {time.strftime(‘%X‘)}")
# 并行执行 1. 先创建在执行
task1 = asyncio.create_task(say_after(1, ‘hello‘))
task2 = asyncio.create_task(say_after(2, ‘world‘))
print(f"started at {time.strftime(‘%X‘)}")
await task1
await task2
print(f"finished at {time.strftime(‘%X‘)}")
# 并行并行 2. 直接运行,使用 asyncio.gather方法
await asyncio.gather(
say_after(2, "A"),
say_after(3, "B"),
say_after(4, "C"),
)
# 并发运行 task 任务
urls = ["http://ww.cn", "http://ww.cn", "http://ww.cn", "http://ww.cn"]
task = []
for i in urls:
task.append(asyncio.create_task(say_after(i, i)))
await asyncio.wait(
task
)
if __name__ == ‘__main__‘:
# 创建协程对象
asyncio.run(main())