Python中的协程是什么 | 您所在的位置:网站首页 › rstrip在python中是什么意思 › Python中的协程是什么 |
协程 在python GIL之下,同一时刻只能有一个线程在运行,那么对于CPU计算密集的程序来说,线程之间的切换开销就成了拖累,而以I/O为瓶颈的程序正是协程所擅长的: Python中的协程经历了很长的一段发展历程。其大概经历了如下三个阶段: 1.最初的生成器变形yield/send; 2.引入@asyncio.coroutine和yield from; 3.在最近的Python3.5版本中引入async/await关键字。 (1)从yield说起 先看一段普通的计算斐波那契续列的代码 def fibs(n): res = [0] * n index = 0 a = 0 b = 1 while index Content-Type: text/html ... (打印出sina的header) www.sina.com.cn header > HTTP/1.1 200 OK www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT ... (打印出163的header) www.163.com header > HTTP/1.0 302 Moved Temporarily www.163.com header > Server: Cdn Cache Server V2.0 ...可见3个连接由一个线程通过coroutine并发完成。 小结 asyncio提供了完善的异步IO支持; 异步操作需要在coroutine中通过yield from完成; 多个coroutine可以封装成一组Task然后并发执行。 您可能感兴趣的文章: 在python中线程和协程的区别是什么 python setup是什么 python什么时候出来的 int在python中什么意思 python里print是什么意思 深究Python中的asyncio库-asyncio简介与关键字 python里int什么意思 Golang教程:goroutine协程 python学完基础学什么 python采用什么开源协议 |
CopyRight 2018-2019 实验室设备网 版权所有 |