如下,多个协程可以并行
await异步等待函数返回, 必须写在在 aysnc内。
除了asyncio.gather(), asyncio.sleep(), 还有 asyncio.wait(), asyncio.wait_for()
import asyncio
import aiohttp
async def f1():
print("f1")
await asyncio.sleep(1)
async with aiohttp.ClientSession() as session:
async with session.get('https://www.baidu.com') as response:
txt = await response.text()
print(txt)
print("f1 end")
return "f1"
async def f2():
print("f2")
await asyncio.sleep(2)
print("f2 end")
return "f2"
async def main1():
result = await asyncio.gather(f1(), f2())
print(result)
async def main2():
task1 = asyncio.create_task(f1())
task2 = asyncio.create_task(f2())
await task1
await task2
#错误的用法,串行运行的
if __name__ == "__main__":
asyncio.run(f2())
asyncio.run(f1())
# 正确的用法
if __name__ == "__main__":
asyncio.run(main1())
# 正确的用法
if __name__ == "__main__":
asyncio.run(main2())