Python之协程(coroutine)
Python之协程(coroutine)
标签(空格分隔): Python进阶
coroutine和generator的区别
generator是数据的产生者。即它pull data 通过 iteration
coroutine是数据的消费者。它push data into pipeline 通过 send
generator的通常用法
generator的作用是可以作为data pipeline使用.
例如可以使用coroutine来做filter,
或者多路的broadcast。
generator通常是yield和for的运用。
示例代码1:
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
for i in fib():
print(i)
用yield接收data,通过for循环将每一步data输出。
下面介绍coroutine, 它的yield接收外部value,而不是保存内部value。
def grep(pattern):
print("Searching for", pattern)
while True:
line = (yield)
if pattern in line:
print line
此处的 yield并不包含任何value,它接受外部.send()方法传过来的value.
search = grep('coroutine')
next(search)
# Output: Searching for coroutine
search.send("I love you")
search.send("Don't you love me?")
search.send("I love coroutines instead!")
# Output: I love coroutines instead!
search.close()
先通过next(),start这个coroutine.
之后每一次调用send(),将参数通过yield传入line中。同时相当于自动运行.next()到下一个value. 最终调用.close()关闭这个协程。
示例1:作为filter使用
import time
def follow(thefile, target):
thefile.seek(0,2) # Go to the end of the file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
target.send(line)
@coroutine
def printer():
while True:
line = (yield)
print line
@coroutine
def grep(pattern,target):
while True:
line = (yield) # Receive a line
if pattern in line:
target.send(line) # Send to next stage
f = open("access-log")
follow(f,grep('python',printer()))
dataflow如下:###
follow将file中的每一行读取,send到coroutine中,grep查找匹配的line,send到下一个coroutine中,printer接收send过来的data,并且输出。 完成整个filter的流程。
follow()-> grep() : send()
grep() -> printer():send()
示例2:作为broadcasting使用
@coroutine
def broadcast(targets):
while True:
item = (yield)
for target in targets:
target.send(item)
f = open("access-log")
p = printer()
follow(f,
broadcast([grep('python',p),
grep('ply',p),
grep('swig',p)])
)
这样就将不同的pattern传入到了不同的coroutine中去,达到了broadcast的目的。
follow-> broadcast: send()
broadcast -> grep('python'): send()
broadcast -> grep('ply') : send()
broadcast -> grep('swig') : send()
grep('python') -> printer:
grep('ply')-> printer:
grep('swig')-> printer:
关于coroutine的更多用法,可见pdf:
http://www.dabeaz.com/coroutines/Coroutines.pdf
Python之协程(coroutine)的更多相关文章
- Python并发编程协程(Coroutine)之Gevent
Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporate routine的缩写,直接翻译 ...
- Python 协程 (Coroutine)
协程 (Coroutine) 什么是协程 协程(微线程)是比线程更轻量化的存在,像一个进程可以拥有多个线程一样,一个线程也可以拥有多个协程 最重要的是,协程不是被操作系统内核所管理,而完全是由程序所控 ...
- 操作系统OS,Python - 协程(Coroutine)
留坑 参考: https://en.wikipedia.org/wiki/Coroutine https://zh.wikipedia.org/wiki/%E5%8D%8F%E7%A8%8B http ...
- (zt)Lua的多任务机制——协程(coroutine)
原帖:http://blog.csdn.net/soloist/article/details/329381 并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上 ...
- 协程coroutine
协程(coroutine)顾名思义就是“协作的例程”(co-operative routines).跟具有操作系统概念的线程不一样,协程是在用户空间利用程序语言的语法语义就能实现逻辑上类似多任务的编程 ...
- Lua的多任务机制——协程(coroutine)
并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上有这么两种多任务技术,一种是抢占式多任务(preemptive multitasking),它让操作系统来决定 ...
- 深入理解Python中协程的应用机制: 使用纯Python来实现一个操作系统吧!!
本文参考:http://www.dabeaz.com/coroutines/ 作者:David Beazley 缘起: 本人最近在学习python的协程.偶然发现了David Beazley的co ...
- 12.python进程\协程\异步IO
进程 创建进程 from multiprocessing import Process import time def func(name): time.sleep(2) print('hello', ...
- 关于Python的协程问题总结
协程其实就是可以由程序自主控制的线程 在python里主要由yield 和yield from 控制,可以通过生成者消费者例子来理解协程 利用yield from 向生成器(协程)传送数据# 传统的生 ...
随机推荐
- 使用jQuery在javascript中自定义事件
js中的自定义事件有attachEvent,addEventListener等等好多种,往往受困于浏览器兼容,而且代码写起来也相当麻烦.jQuery为我们解决了这个问题,几行代码就可以很好的实现事件的 ...
- 洛谷 P3990 [SHOI2013]超级跳马 解题报告
P3990 [SHOI2013]超级跳马 题目描述 现有一个\(n\) 行 \(m\) 列的棋盘,一只马欲从棋盘的左上角跳到右下角.每一步它向右跳奇数列,且跳到本行或相邻行.跳越期间,马不能离开棋盘. ...
- 【bzoj2733】 HNOI2012—永无乡
http://www.lydsy.com/JudgeOnline/problem.php?id=2733 (题目链接) 题意 给出图上$n$个点,每个点有一个点权,每次询问一个连通块中点权第$K$小的 ...
- 使用IPMI控制/监控Linux服务器
1 IPMI简述 IPMI提供了很多丰富功能,我使用的功能,说得大白话一点,就是: 1.获取本设备的硬件信息:包括CPU和主板的温度.电压.风扇转速. 2.在设备A上,通过命令,控制远程设 ...
- response.sendRedirect()和request.getRequestDispatcher().forward(request,response)的区别
转发方式:request.getRequestDispatcher().forward(); 重定向方式:response.sendRedirect(); 下面是HttpServletRespons ...
- Activity的setResult方法
Activity的setResult方法http://blog.csdn.net/dinglin_87/article/details/8970144 调用setResult()方法必须在finish ...
- Java利用poi生成word(包含插入图片,动态表格,行合并)
转(小改): Java利用poi生成word(包含插入图片,动态表格,行合并) 2018年12月20日 09:06:51 wjw_11093010 阅读数:70 Java利用poi生成word(包含插 ...
- Docker 安装tensorflow
安装DOCKER 1. https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/ nstall from a packag ...
- etcd启用https服务
目录 cfssl相关工具下载 生成etcd所需要的ssl证书 生成ca证书 生成etcd服务端证书 生成etcd客户端证书 修改etcd集群配置文件 重启etcd集群 验证集群健康情况 关于etcd的 ...
- Hadoop生态圈-使用phoenix的API进行JDBC编程
Hadoop生态圈-使用phoenix的API进行JDBC编程 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.