Python异步协程asyncawaitasyncio
引⾃:blog.csdn/sunt2018/article/details/105138121异步IO asyncio协程
asyncio 是python3.4 引⼊的,内置的对异步IO的⽀持。
asyncio编程是⼀个消息循环,我们从asyncio中获取⼀个EventLoop引⽤
然后把协程放到EventLoop中执⾏,就实现了异步IO
协程常见名字
先了解以下名词,有助于理解程序编写
event_loop 事件循环:程序开启⼀个循环,我们把函数注册到loop⾥,满⾜条件就会执⾏
coroutine 协程: async def 定义的函数,它不能直接执⾏,返回的是协程对象,它要注册到loop中,由loop去执⾏调⽤
task 任务:⼀个协程对象就是⼀个原⽣可以挂起的函数,任务则是对协程对象进⼀步封装,增加了任务的各种状态,(⽐如未执⾏,执⾏中,执⾏结束,返回结果等等?。)
task 是 future的⼦类
future : 代表将来执⾏或没有执⾏的任务的结果,它个task没有本质区别
async/await : python3.5 ⽤于定义协程的关键字
创建⼀个协程 Coroutine
import asyncio,time
# 记录开始时间
now = lambda: time.time()
start = now()
# 01.定义⼀个协程
async def do_work(num):
print("num:",num)
coroutine = do_work(1)
# 02.创建事件循环
loop = _event_loop()
# 03.将协程对象放⼊事件循环中
loop.run_until_complete(coroutine)
# 记录结束时间
print(now() - start)
创建⼀个任务 Task
loop.run_until_complete⽅法传⼊协程,⾃动将协程装成任务task,它也可以直接接收task
创建task 使⽤以下⽅法都可以
task是future的⼦类。
isinstance(task,asyncio.Future) 返回Ture
import asyncio,time
# 记录开始时间
await和async使用方法now = lambda: time.time()
start = now()
# 01.定义⼀个协程
async def do_work(num):
print("num:",num)
coroutine = do_work(1)
# 02.创建事件循环
loop = _event_loop()
# 03.创建任务Task
task = sure_future(coroutine)
# 或者下⾯的⽅式创建task也可以
# task = ate_task(coroutine)
# 04.将任务注册到事件循环中
loop.run_until_complete(task)
# 记录结束时间
print(now() - start)
获取返回结果回调函数future/直接使⽤Task获取import asyncio,time
# 记录开始时间
now = lambda: time.time()
start = now()
# 01.定义⼀个协程
async def do_work(num):
print("num:",num)
return "num is {}".format(num)
coroutine = do_work(3)
# 02.定义回调函数
def callback(future):
print('result is',sult())
# 03.创建事件循环
loop = _event_loop()
# 04.创建任务Task
task = ate_task(coroutine)
# 05.给task任务绑定回调函数
task.add_done_callback(callback)
# 06.将任务注册到事件循环中
loop.run_until_complete(task)
# 记录结束时间
print(now() - start)
不绑定回调,直接使⽤Task的结果
阻塞 await
import asyncio,time
# 记录开始时间
now = lambda: time.time()
start = now()
async def do_work(num):
print("num:",num)
await asyncio.sleep(num)
return "sleep is {}".format(num) coroutine = do_work(3)
# 02.创建事件循环
loop = _event_loop()
# 03.创建任务Task
task = ate_task(coroutine)
sult())
# 04.将任务注册到事件循环中
loop.run_until_complete(task)
# 记录结束时间
print(now() - start)
sult())
asyncio 实现并发import asyncio,time
# 记录开始时间
now = lambda: time.time()
start = now()
# 01.定义⼀个协程
async def do_work(num):
print("num:",num)
await asyncio.sleep(num)
return "sleep is {}".format(num) coroutine1 = do_work(1)
coroutine2 = do_work(2)
coroutine3 = do_work(3)
# 02.创建任务Task
tasks =[
]
# 02.创建事件循环
loop = _event_loop()
# 04.将任务注册到事件循环中
loop.run_until_complete(asyncio.wait(tasks)) # 记录结束时间
print(now() - start)
for task in tasks:
sult())
协程嵌套
import time
import asyncio
async def do_work(x):
print("do...")
await asyncio.sleep(x)
return 'Done result'
async def main():
coroutine1 = do_work(1)
coroutine2 = do_work(2)
coroutine3 = do_work(4)
tasks = [
]
# --------------------------------------------
# 获取返回结果的⽅式 1
dones,pendings = await asyncio.wait(tasks)
# dones 是任务
for task in dones:
sult())
# --------------------------------------------
# 将协程main 放⼊到 loop中
loop = _event_loop()
loop.run_until_complete(main())
获取返回结果的⽅式2
results =  await asyncio.gather(*tasks)
for result in results():
print(result)
# 获取⽅式3,不在main中获取,⽽是在外⾯获取
async def main:
# .....
return await asyncio.gather(*tasks)
results = loop.run_until_complete(main())
for result in results():
print(result)
# 获取⽅式4,不在main中获取,⽽是在外⾯获取
async def main:
# .....
return await asyncio.wait(tasks)
dones,pendings = loop.run_until_complete(main())
for task in dones:
sult())
# 获取⽅式5,还是在main中
for task in asyncio.as_complete(tasks):
result = await task
print(result)
协程的停⽌
future 中的⼏种状态
Pending 创建future的时候,task为 pending
Running 事件循环执⾏的时候,task是running
Done 执⾏完毕 task状态是done
Cancelled 任务取消
import time
import asyncio
async def do_work(x):
print("do...")
await asyncio.sleep(x)
return 'Done result'
coroutine1 = do_work(1)
coroutine2 = do_work(2)
coroutine3 = do_work(4)
tasks = [
]
start = time.time()
loop = _event_loop()
try:
loop.run_until_complete(asyncio.wait(tasks)) except KeyboardInterrupt as e:
for task in asyncio.Task.all_tasks():
print(task.cancel())
loop.stop()
loop.run_forever()
finally:
loop.close()
print(time.time() - start)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。