我们都知道,现在的服务器开发对于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将协程注册到事件循环,并启动事件循环。

例如:

  1. import asyncio
  2. async def fun():
  3. print('hello word')
  4. loop = asyncio.get_event_loop()
  5. loop.run_until_complete(fun())

【二】任务对象task

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

例如:

  1. import asyncio
  2. async def fun():
  3. print('hello word')
  4. return 'miao'
  5. loop = asyncio.get_event_loop()
  6. task = loop.create_task(fun())
  7. print(task)
  8. loop.run_until_complete(task)
  9. 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对象,通过该对象可以获取协程返回值。如果回调需要多个参数,可以通过偏函数导入。

例如:

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

也可以使用ensure_future获取返回值

例如:

  1. import asyncio
  2. async def fun():
  3. print('hello word')
  4. return 'miao'
  5. #def callback(future):
  6. #print('Callback: ', future.result())
  7. loop = asyncio.get_event_loop()
  8. #task = loop.create_task(fun())
  9. #task.add_done_callback(callback)
  10. task = asyncio.ensure_future(fun())
  11. loop.run_until_complete(task)
  12. print('the fun() return is: {}'.format(task.result()))

【四】await阻塞

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

例如:

  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. def main():
  10. loop = asyncio.get_event_loop()
  11. print("begin")
  12. loop.run_until_complete(hello())
  13. loop.close()
  14. print("end")
  15. if __name__ == "__main__":
  16. main()

【五】3.6更新

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

例如:

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

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

例如:

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

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

例如:

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

【六】协程并发

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

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

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

例如:

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

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

【七】协程嵌套

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

例如:

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

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

  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协程的结果。

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

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

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

也可以使用asyncio的as_completed方法

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

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

【八】协程停止

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

例如:

  1. import asyncio
  2. import time
  3. now = lambda: time.time()
  4. async def do_some_work(x):
  5. print('Waiting: ', x)
  6. await asyncio.sleep(x)
  7. return 'Done after {}s'.format(x)
  8. coroutine1 = do_some_work(1)
  9. coroutine2 = do_some_work(2)
  10. coroutine3 = do_some_work(4)
  11. tasks = [
  12. asyncio.ensure_future(coroutine1),
  13. asyncio.ensure_future(coroutine2),
  14. asyncio.ensure_future(coroutine3)
  15. ]
  16. start = now()
  17. loop = asyncio.get_event_loop()
  18. try:
  19. loop.run_until_complete(asyncio.wait(tasks))
  20. except KeyboardInterrupt as e:
  21. print(asyncio.Task.all_tasks())
  22. for task in asyncio.Task.all_tasks():
  23. print(task.cancel())
  24. loop.stop()
  25. loop.run_forever()
  26. finally:
  27. loop.close()
  28. 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函数即可。

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

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

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

  1. import asyncio
  2. import time
  3. now = lambda: time.time()
  4. from threading import Thread
  5. def start_loop(loop):
  6. asyncio.set_event_loop(loop)
  7. loop.run_forever()
  8. def more_work(x):
  9. print('More work {}'.format(x))
  10. time.sleep(x)
  11. print('Finished more work {}'.format(x))
  12. start = now()
  13. new_loop = asyncio.new_event_loop()
  14. t = Thread(target=start_loop, args=(new_loop,))
  15. t.start()
  16. print('TIME: {}'.format(time.time() - start))
  17. new_loop.call_soon_threadsafe(more_work, 6)
  18. 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左右。

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

python——asyncio模块实现协程、异步编程的更多相关文章

  1. 运筹帷幄决胜千里,Python3.10原生协程asyncio工业级真实协程异步消费任务调度实践

    我们一直都相信这样一种说法:协程是比多线程更高效的一种并发工作方式,它完全由程序本身所控制,也就是在用户态执行,协程避免了像线程切换那样产生的上下文切换,在性能方面得到了很大的提升.毫无疑问,这是颠扑 ...

  2. python 多协程异步IO爬取网页加速3倍。

    from urllib import request import gevent,time from gevent import monkey#该模块让当前程序所有io操作单独标记,进行异步操作. m ...

  3. 线程池、进程池(concurrent.futures模块)和协程

    一.线程池 1.concurrent.futures模块 介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 Pro ...

  4. python进阶——进程/线程/协程

    1 python线程 python中Threading模块用于提供线程相关的操作,线程是应用程序中执行的最小单元. #!/usr/bin/env python # -*- coding:utf-8 - ...

  5. 12.python进程\协程\异步IO

    进程 创建进程 from multiprocessing import Process import time def func(name): time.sleep(2) print('hello', ...

  6. Python全栈开发-Day10-进程/协程/异步IO/IO多路复用

    本节内容 多进程multiprocessing 进程间的通讯 协程 论事件驱动与异步IO Select\Poll\Epoll——IO多路复用   1.多进程multiprocessing Python ...

  7. Python 8 协程/异步IO

    协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来 ...

  8. Python程序中的协程操作-gevent模块

    目录 一.安装 二.Gevent模块介绍 2.1 用法介绍 2.2 例:遇到io主动切换 2.3 查看threading.current_thread().getName() 三.Gevent之同步与 ...

  9. 31、Python程序中的协程操作(greenlet\gevent模块)

    一.协程介绍 协程:是单线程下的并发,又称微线程,纤程.英文名Coroutine.一句话说明什么是协程:协程是一种用户态的轻量级线程,即协程是由用户程序自己控制调度的. 对比操作系统控制线程的切换,用 ...

随机推荐

  1. 【Mybatis】Mybatis基本构成

    SqlSessionFactoryBuilder(构造器):它会根据配置信息或者代码来生成SqlSessionFactory(工厂接口) SqlSessionFactory:依靠工厂来生成SqlSes ...

  2. 【CF886E】Maximum Element DP

    [CF886E]Maximum Element 题意:小P有一个1-n的序列,他想找到整个序列中最大值的出现位置,但是他觉得O(n)扫一遍太慢了,所以它采用了如下方法: 1.逐个遍历每个元素,如果这个 ...

  3. python pytest测试框架介绍二

    在介绍一中简单介绍了pytest的安装和简单使用,接下来我们就要实际了解pytest了 一.pytest的用例发现规则 pytest可以在不同的函数.包中发现用例,发现的规则如下 文件名以test_开 ...

  4. AndroidStudio 使用Release签名进行Debug

    extends:http://blog.csdn.net/h3c4lenovo/article/details/42011887 , http://www.linuxidc.com/Linux/201 ...

  5. dhroid - DhNet 网络http工具

    extends:http://www.eoeandroid.com/thread-327440-1-1.html     DhNet net=new DhNet("路劲"); ne ...

  6. Unity3D NGUI 二 NGUI Button怎样接受用户点击并调用函数,具体方法名称是什么

    a.直接监听事件 把下面脚本直接绑定在按钮上,当按钮点击时就可以监听到,这种方法不太好很不灵活. void OnClick(){ Debug.Log("Button is Click!!!& ...

  7. Java虚拟机一

    Java发展至今,出现了很多Java虚拟机,从最初的Classic的Java虚拟机到Exact VM虚拟机,到现在最终被大规模部署和应用的是Hotspot虚拟机.       整数在Java虚拟机中的 ...

  8. iOS - 网址、链接、网页地址、下载链接等正则表达式匹配(解决url包含中文不能编码的问题)

    DNS规定,域名中的标号都由英文字母和数字组成,每一个标号不超过63个字符,也不区分大小写字母.标号中除连字符(-)外不能使用其他的标点符号.级别最低的域名写在最左边,而级别最高的域名写在最右边.由多 ...

  9. quartz 任务时间调度入门使用

    这一小节主要是针对cronschedule用法进行讨论,首先讲一下cronschedule基础知识点: 一个cronschedule至少有6个字符(或者7个字符),空格作为间隔,比如 0 * * * ...

  10. 彻底关闭window10 专业版 企业版 windows defender

    按照上面图中的,关闭windows defender 设置为已启用,这样就可以彻底关闭 windows defender了