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 向生成器(协程)传送数据# 传统的生 ...
随机推荐
- AtCoder Grand Contest 003
AtCoder Grand Contest 003 A - Wanna go back home 翻译 告诉你一个人每天向哪个方向走,你可以自定义他每天走的距离,问它能否在最后一天结束之后回到起点. ...
- 编译安装haproxy开启支持SSL
1.下载程序包 # wget http://www.haproxy.org/download/1.7/src/haproxy-1.7.5.tar.gz # tar xvf haproxy-1.7.5. ...
- Andrioid Studio生成jar, aar包
在Android Studio中对一个自己库进行生成操作时将会同时生成*.jar与*.aar文件.分别存储位置:*.jar:库/build/intermediates/bundles/debug(re ...
- 轻量高效的开源JavaScript插件和库 【转】
图片 布局 轮播图 弹出层 音频视频 编辑器 字符串 表单 存储 动画 时间 其它 加载器 构建工具 测试 包管理器 CDN 图片 baguetteBox.js - 是一个简单易用的响应式图像灯箱效果 ...
- 初识Unity Mesh
Mesh概念:Mesh是Unity中的一个组件,称为网格组件.通俗的讲,Mesh是指模型的网格,3D模型是由多边形拼接而成,而多边形实际上是由多个三角形拼接而成的.所以一个3D模型的表面其实是由多个彼 ...
- 题解【bzoj4587 & bzoj4408 [FJOI2016]神秘数】
Description \(n\) 个数的序列,每次询问一个区间,求最小的一个数使得不能用这个区间中的数之和表示. \(n \leq 10^5, \sum a_i \leq 10^9\) 这两个题一个 ...
- 三、Linux学习之命令基本格式篇
一.命令格式 命令 [选项] [参数] 注意: 1.和别命令使用不遵循此格式 2.当有多个选项时,可以写在一起 3.简化选项与完整选项(-a 等价于--all) 4.中括号为可选,意思是可以有可以没有 ...
- MySQL内存计算器
MySQL如何使用内存? 首先,介绍MySQL使用内存的一些方法: 1. 会话级别的内存消耗(连接私有内存):如sort_buffer_size等,每个会话都会开辟一个sort_buffer_size ...
- label和fieldset标签
一.label标签 作用:可以通过for属性关联input标签的 id 属性,这样可以实现在点击label标签的内容时,可以使input文本框中获取输入的光标. <body> <la ...
- P2043 质因子分解
P2043 质因子分解 题目描述 对N!进行质因子分解. 输入输出格式 输入格式: 输入数据仅有一行包含一个正整数N,N<=10000. 输出格式: 输出数据包含若干行,每行两个正整数p,a,中 ...