跳到主要内容

异步协程操作

异步协程本身很简单,引入 asyncio 包就行,但是python3.0更新之后的写法不太一样,需要使用事件循环
如下:

import asyncio
import time

async def func1():
print('111')
await asyncio.sleep(3) # 使用 asyncio.sleep() 替代 time.sleep()
print('111')

async def func2():
print('222')
await asyncio.sleep(4) # 使用 asyncio.sleep() 替代 time.sleep()
print('222')

async def func3():
print('333')
await asyncio.sleep(2) # 使用 asyncio.sleep() 替代 time.sleep()
print('333')

if __name__ == '__main__':
f1 = func1()
f2 = func2()
f3 = func3()
# 一次性启动多个(协程)
tasks = [f1,f2,f3]
# 创建事件循环对象
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
t1 = time.time()
# 一次性启动多个(协程)
loop.run_until_complete(asyncio.gather(*tasks))
t2 = time.time()
print(t2 - t1)