python——asyncio模块实现协程、异步编程

我们都知道,现在的服务器开发对于IO调度的优先级控制权已经不再依靠系统,都希望采用协程的方式实现高效的并发任务,如js、lua等在异步协程方面都做的很强大。

Python在3.4版本也加入了协程的概念,并在3.5确定了基本完善的语法和实现方式。同时3.6也对其进行了如解除了await和yield在同一个函数体限制等相关的优化。

event_loop 事件循环:程序开启一个无限的循环,程序员会把一些函数注册到事件循环上。当满足事件发生的时候,调用相应的协程函数。
coroutine 协程:协程对象,指一个使用async关键字定义的函数,它的调用不会立即执行函数,而是会返回一个协程对象。协程对象需要注册到事件循环,由事件循环调用。
task 任务:一个协程对象就是一个原生可以挂起的函数,任务则是对协程进一步封装,其中包含任务的各种状态。
future: 代表将来执行或没有执行的任务的结果。它和task上没有本质的区别
async/await 关键字:python3.5 用于定义协程的关键字,async定义一个协程,await用于挂起阻塞的异步调用接口。

【一】创建协程

首先定义一个协程,在def前加入async声明,就可以定义一个协程函数。

一个协程函数不能直接调用运行,只能把协程加入到事件循环loop中。asyncio.get_event_loop方法可以创建一个事件循环,然后使用run_until_complete将协程注册到事件循环,并启动事件循环。

例如:

[python] view plain copy
 
  1. import asyncio  
  2.    
  3. async def fun():  
  4.     print('hello word')  
  5.    
  6. loop = asyncio.get_event_loop()  
  7.   
  8. loop.run_until_complete(fun())  

【二】任务对象task

协程对象不能直接运行,在注册事件循环的时候,其实是run_until_complete方法将协程包装成为了一个任务(task)对象。所谓task对象是Future类的子类。保存了协程运行后的状态,用于未来获取协程的结果。

例如:

[python] view plain copy
 
  1. import asyncio  
  2.    
  3. async def fun():  
  4.     print('hello word')  
  5.     return 'miao'  
  6.    
  7. loop = asyncio.get_event_loop()  
  8. task = loop.create_task(fun())  
  9. print(task)  
  10. loop.run_until_complete(task)  
  11. print(task)  


创建task后,task在加入事件循环之前是pending状态,因为do_some_work中没有耗时的阻塞操作,task很快就执行完毕了。后面打印的finished状态。
asyncio.ensure_future 和 loop.create_task都可以创建一个task,run_until_complete的参数是一个futrue对象。当传入一个协程,其内部会自动封装成task,task是Future的子类。isinstance(task, asyncio.Future)将会输出True。



【三】绑定回调

在task执行完毕的时候可以获取执行的结果,回调的最后一个参数是future对象,通过该对象可以获取协程返回值。如果回调需要多个参数,可以通过偏函数导入。

例如:

[python] view plain copy
 
  1. import asyncio  
  2.    
  3. async def fun():  
  4.     print('hello word')  
  5.     return 'miao'  
  6.    
  7.   
  8. def callback(future):  
  9.     print('Callback: ', future.result())  
  10.    
  11. loop = asyncio.get_event_loop()  
  12. task = loop.create_task(fun())  
  13. #print(task)  
  14. task.add_done_callback(callback)  
  15. loop.run_until_complete(task)  
  16. #print(task)  


也可以使用ensure_future获取返回值

例如:

[python] view plain copy
 
  1. import asyncio  
  2.    
  3. async def fun():  
  4.     print('hello word')  
  5.     return 'miao'  
  6.    
  7.   
  8. #def callback(future):  
  9.     #print('Callback: ', future.result())  
  10.    
  11. loop = asyncio.get_event_loop()  
  12. #task = loop.create_task(fun())  
  13. #task.add_done_callback(callback)  
  14. task = asyncio.ensure_future(fun())  
  15. loop.run_until_complete(task)  
  16.   
  17. print('the fun() return is: {}'.format(task.result()))  
  18.   
  19.    



【四】await阻塞

使用async可以定义协程对象,使用await可以针对耗时的操作进行挂起,就像生成器里的yield一样,函数让出控制权。协程遇到await,事件循环将会挂起该协程,执行别的协程,直到其他的协程也挂起或者执行完毕,再进行下一个协程的执行。
耗时的操作一般是一些IO操作,例如网络请求,文件读取等。我们使用asyncio.sleep函数来模拟IO操作。协程的目的也是让这些IO操作异步化。

例如:

[python] view plain copy
 
  1. #coding:utf-8    
  2. import asyncio  
  3. import threading    
  4. import time   
  5. async def hello():  
  6.     print("hello 1")  
  7.     r = await asyncio.sleep(1)  
  8.     print("hello 2")  
  9.     
  10.   
  11. def main():  
  12.     loop = asyncio.get_event_loop()  
  13.   
  14.     print("begin")  
  15.     loop.run_until_complete(hello())   
  16.     loop.close()  
  17.     print("end")  
  18.   
  19.   
  20. if __name__ == "__main__":  
  21.     main()  


【五】3.6更新

①可以在同一个协程函数中同时使用await和yield

例如:

[python] view plain copy
 
  1. import asyncio  
  2. async def ticker(delay, to):  
  3.     for i in range(to):  
  4.         yield i  
  5.         await asyncio.sleep(delay)  
  6.   
  7.   
  8. async def run():  
  9.     async for i in ticker(1, 10):  
  10.         print(i)  
  11.   
  12. loop = asyncio.get_event_loop()  
  13. try:  
  14.     loop.run_until_complete(run())  
  15. finally:  
  16.   
  17.     loop.close()  

顺带一提,yield 我们可以暂且认为是一种中断机制(详情可以参考官方文档,这种解释只是便于说明await)

例如:

[python] view plain copy
 
  1. def a():  
  2.     print("first")    
  3.     yield     
  4.     print("second")   
  5.     yield    
  6.     print("end")   
  7.     yield   
  8.   
  9. if __name__ == "__main__":  
  10.   
  11.     g1=a()  
  12.     print("next1")  
  13.     g1.__next__()  
  14.     print("next2")  
  15.     g1.__next__()  
  16.     print("next3")  
  17.     g1.__next__()  


②允许在协程函数中异步推导式

例如:

[python] view plain copy
 
  1. async def ticker(delay, to):  
  2.     for i in range(to):  
  3.         yield i  
  4.         await asyncio.sleep(delay)  
  5.   
  6. async def run():  
  7.     result = [i async for i in ticker(1, 10) if i%2]  
  8.     print(result)  
  9. import asyncio  
  10. loop = asyncio.get_event_loop()  
  11. try:  
  12.   
  13.     loop.run_until_complete(run())  
  14. finally:  
  15.   
  16.     loop.close()  


【六】协程并发

定义tasks时可以设置多个ensure,也可以像多线程那样用append方法实现

[python] view plain copy
 
  1. tasks = [  
  2.     asyncio.ensure_future(coroutine1),  
  3.     asyncio.ensure_future(coroutine2),  
  4.     asyncio.ensure_future(coroutine3)  
  5. ]  
  6.   
  7. for i in range(4, 6):    
  8.     tasks.append(asyncio.ensure_future(do_some_work(i)))  



当遇到阻塞时可以使用await让其他协程继续工作

例如:

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4.    
  5. async def do_some_work(x):  
  6.     print('Waiting: ', x)  
  7.    
  8.     await asyncio.sleep(x)  
  9.     return 'Done after {}s'.format(x)  
  10.    
  11. coroutine1 = do_some_work(1)  
  12. coroutine2 = do_some_work(2)  
  13. coroutine3 = do_some_work(3)   
  14.   
  15. tasks = [  
  16.     asyncio.ensure_future(coroutine1),  
  17.     asyncio.ensure_future(coroutine2),  
  18.     asyncio.ensure_future(coroutine3)  
  19. ]  
  20.   
  21. for i in range(4, 6):    
  22.     tasks.append(asyncio.ensure_future(do_some_work(i)))  
  23.    
  24. loop = asyncio.get_event_loop()  
  25.   
  26. start = now()  
  27. loop.run_until_complete(asyncio.wait(tasks))  
  28.    
  29. for task in tasks:  
  30.     print('Task ret: ', task.result())  
  31.    
  32. print('TIME: ', now() - start)  


通过运行时间可以看出aysncio实现了并发。asyncio.wait(tasks) 也可以使用 asyncio.gather(*tasks) ,前者接受一个task列表,后者接收一堆task。

【七】协程嵌套

使用async可以定义协程,协程用于耗时的io操作,我们也可以封装更多的io操作过程,这样就实现了嵌套的协程,即一个协程中await了另外一个协程,如此连接起来。

例如:

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4. async def do_some_work(x):  
  5.     print('Waiting: ', x)  
  6.    
  7.     await asyncio.sleep(x)  
  8.     return 'Done after {}s'.format(x)  
  9.    
  10. async def main():  
  11.     coroutine1 = do_some_work(1)  
  12.     coroutine2 = do_some_work(2)  
  13.     coroutine3 = do_some_work(4)  
  14.    
  15.     tasks = [  
  16.         asyncio.ensure_future(coroutine1),  
  17.         asyncio.ensure_future(coroutine2),  
  18.         asyncio.ensure_future(coroutine3)  
  19.     ]  
  20.    
  21.     dones, pendings = await asyncio.wait(tasks)  
  22.    
  23.     for task in dones:  
  24.         print('Task ret: ', task.result())  
  25.    
  26. start = now()  
  27.    
  28. loop = asyncio.get_event_loop()  
  29. loop.run_until_complete(main())  
  30.    
  31. print('TIME: ', now() - start)  



如果使用的是 asyncio.gather创建协程对象,那么await的返回值就是协程运行的结果。

[python] view plain copy
 
  1. #dones, pendings = await asyncio.wait(tasks)  
  2.     #for task in dones:  
  3.     #print('Task ret: ', task.result())  
  4. results = await asyncio.gather(*tasks)  
  5. for result in results:  
  6.     print('Task ret: ', result)  



不在main协程函数里处理结果,直接返回await的内容,那么最外层的run_until_complete将会返回main协程的结果。

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4. async def do_some_work(x):  
  5.     print('Waiting: ', x)  
  6.    
  7.     await asyncio.sleep(x)  
  8.     return 'Done after {}s'.format(x)  
  9.    
  10. async def main():  
  11.     coroutine1 = do_some_work(1)  
  12.     coroutine2 = do_some_work(2)  
  13.     coroutine3 = do_some_work(4)  
  14.    
  15.     tasks = [  
  16.         asyncio.ensure_future(coroutine1),  
  17.         asyncio.ensure_future(coroutine2),  
  18.         asyncio.ensure_future(coroutine3)  
  19.     ]  
  20.    
  21.     return await asyncio.gather(*tasks)  
  22.    
  23. start = now()  
  24. loop = asyncio.get_event_loop()  
  25. results = loop.run_until_complete(main())  
  26. for result in results:  
  27.     print('Task ret: ', result)  
  28.    
  29. print('TIME: ', now() - start)  



或者返回使用asyncio.wait方式挂起协程。

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4. async def do_some_work(x):  
  5.     print('Waiting: ', x)  
  6.    
  7.     await asyncio.sleep(x)  
  8.     return 'Done after {}s'.format(x)  
  9.    
  10. async def main():  
  11.     coroutine1 = do_some_work(1)  
  12.     coroutine2 = do_some_work(2)  
  13.     coroutine3 = do_some_work(4)  
  14.    
  15.     tasks = [  
  16.         asyncio.ensure_future(coroutine1),  
  17.         asyncio.ensure_future(coroutine2),  
  18.         asyncio.ensure_future(coroutine3)  
  19.     ]  
  20.    
  21.     return await asyncio.wait(tasks)  
  22.    
  23. start = now()  
  24.    
  25. loop = asyncio.get_event_loop()  
  26. done, pending = loop.run_until_complete(main())  
  27.    
  28. for task in done:  
  29.     print('Task ret: ', task.result())  
  30.    
  31. print('TIME: ', now() - start)  


也可以使用asyncio的as_completed方法

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4. async def do_some_work(x):  
  5.     print('Waiting: ', x)  
  6.    
  7.     await asyncio.sleep(x)  
  8.     return 'Done after {}s'.format(x)  
  9.    
  10. async def main():  
  11.     coroutine1 = do_some_work(1)  
  12.     coroutine2 = do_some_work(2)  
  13.     coroutine3 = do_some_work(4)  
  14.    
  15.     tasks = [  
  16.         asyncio.ensure_future(coroutine1),  
  17.         asyncio.ensure_future(coroutine2),  
  18.         asyncio.ensure_future(coroutine3)  
  19.     ]  
  20.     for task in asyncio.as_completed(tasks):  
  21.         result = await task  
  22.         print('Task ret: {}'.format(result))  
  23.    
  24. start = now()  
  25.    
  26. loop = asyncio.get_event_loop()  
  27. done = loop.run_until_complete(main())  
  28. print('TIME: ', now() - start)  



由此可见,协程的调用和组合十分的灵活,我们可以发挥想象尽情的浪

【八】协程停止

future对象有几个状态:
Pending
Running
Done
Cancelled
创建future的时候,task为pending,事件循环调用执行的时候当然就是running,调用完毕自然就是done,如果需要停止事件循环,就需要先把task取消。可以使用asyncio.Task获取事件循环的task

例如:

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4.    
  5. async def do_some_work(x):  
  6.     print('Waiting: ', x)  
  7.    
  8.     await asyncio.sleep(x)  
  9.     return 'Done after {}s'.format(x)  
  10.    
  11. coroutine1 = do_some_work(1)  
  12. coroutine2 = do_some_work(2)  
  13. coroutine3 = do_some_work(4)  
  14.    
  15. tasks = [  
  16.     asyncio.ensure_future(coroutine1),  
  17.     asyncio.ensure_future(coroutine2),  
  18.     asyncio.ensure_future(coroutine3)  
  19. ]  
  20.    
  21. start = now()  
  22.    
  23. loop = asyncio.get_event_loop()  
  24. try:  
  25.     loop.run_until_complete(asyncio.wait(tasks))  
  26. except KeyboardInterrupt as e:  
  27.     print(asyncio.Task.all_tasks())  
  28.     for task in asyncio.Task.all_tasks():  
  29.         print(task.cancel())  
  30.     loop.stop()  
  31.     loop.run_forever()  
  32. finally:  
  33.     loop.close()  
  34.    
  35. print('TIME: ', now() - start)  


启动事件循环之后,马上ctrl+c,会触发run_until_complete的执行异常 KeyBorardInterrupt。然后通过循环asyncio.Task取消future

True表示cannel成功,loop stop之后还需要再次开启事件循环,最后在close,不然会报错。

循环task,逐个cancel是一种方案,可是正如上面我们把task的列表封装在main函数中,main函数外进行事件循环的调用。这个时候,main相当于最外出的一个task,那么处理包装的main函数即可。

[python] view plain copy
 
  1. import asyncio  
  2.    
  3. import time  
  4.    
  5. now = lambda: time.time()  
  6.    
  7. async def do_some_work(x):  
  8.     print('Waiting: ', x)  
  9.    
  10.     await asyncio.sleep(x)  
  11.     return 'Done after {}s'.format(x)  
  12.    
  13. async def main():  
  14.     coroutine1 = do_some_work(1)  
  15.     coroutine2 = do_some_work(2)  
  16.     coroutine3 = do_some_work(4)  
  17.    
  18.     tasks = [  
  19.         asyncio.ensure_future(coroutine1),  
  20.         asyncio.ensure_future(coroutine2),  
  21.         asyncio.ensure_future(coroutine3)  
  22.     ]  
  23.     done, pending = await asyncio.wait(tasks)  
  24.     for task in done:  
  25.         print('Task ret: ', task.result())  
  26.    
  27. start = now()  
  28.    
  29. loop = asyncio.get_event_loop()  
  30. task = asyncio.ensure_future(main())  
  31. try:  
  32.     loop.run_until_complete(task)  
  33. except KeyboardInterrupt as e:  
  34.     print(asyncio.Task.all_tasks())  
  35.     print(asyncio.gather(*asyncio.Task.all_tasks()).cancel())  
  36.     loop.stop()  
  37.     loop.run_forever()  
  38. finally:  
  39.     loop.close()  


【九】不同线程的事件循环

很多时候,我们的事件循环用于注册协程,而有的协程需要动态的添加到事件循环中。一个简单的方式就是使用多线程。当前线程创建一个事件循环,然后在新建一个线程,在新线程中启动事件循环。当前线程不会被block。

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4. from threading import Thread  
  5.    
  6. def start_loop(loop):  
  7.     asyncio.set_event_loop(loop)  
  8.     loop.run_forever()  
  9.    
  10. def more_work(x):  
  11.     print('More work {}'.format(x))  
  12.     time.sleep(x)  
  13.     print('Finished more work {}'.format(x))  
  14.    
  15. start = now()  
  16. new_loop = asyncio.new_event_loop()  
  17. t = Thread(target=start_loop, args=(new_loop,))  
  18. t.start()  
  19. print('TIME: {}'.format(time.time() - start))  
  20.    
  21. new_loop.call_soon_threadsafe(more_work, 6)  
  22. new_loop.call_soon_threadsafe(more_work, 3)  

启动上述代码之后,当前线程不会被block,新线程中会按照顺序执行call_soon_threadsafe方法注册的more_work方法,后者因为time.sleep操作是同步阻塞的,因此运行完毕more_work需要大致6 + 3

【十】新线程协程

新线程协程的话,可以在主线程中创建一个new_loop,然后在另外的子线程中开启一个无限事件循环。主线程通过run_coroutine_threadsafe新注册协程对象。这样就能在子线程中进行事件循环的并发操作,同时主线程又不会被block。一共执行的时间大概在6s左右。

[python] view plain copy
 
  1. import asyncio  
  2. import time  
  3. now = lambda: time.time()  
  4. from threading import Thread  
  5.    
  6.   
  7. def start_loop(loop):  
  8.     asyncio.set_event_loop(loop)  
  9.     loop.run_forever()  
  10.    
  11. async def do_some_work(x):  
  12.     print('Waiting {}'.format(x))  
  13.     await asyncio.sleep(x)  
  14.     print('Done after {}s'.format(x))  
  15.    
  16. def more_work(x):  
  17.     print('More work {}'.format(x))  
  18.     time.sleep(x)  
  19.     print('Finished more work {}'.format(x))  
  20.    
  21. start = now()  
  22. new_loop = asyncio.new_event_loop()  
  23. t = Thread(target=start_loop, args=(new_loop,))  
  24. t.start()  
  25. print('TIME: {}'.format(time.time() - start))  
  26.    
  27. asyncio.run_coroutine_threadsafe(do_some_work(6), new_loop)  
  28. asyncio.run_coroutine_threadsafe(do_some_work(4), new_loop)  


原文地址:https://www.cnblogs.com/yanzi-meng/p/8533734.html