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 向生成器(协程)传送数据# 传统的生 ...
随机推荐
- 查看临时表空间占用最多的用户与SQL
select sess.username, sql.sql_text, sort1.blocks from v$session sess, v$sqlarea sql, v$sort_usage ...
- 【BZOJ4999】This Problem Is Too Simple!(线段树)
[BZOJ4999]This Problem Is Too Simple!(线段树) 题面 BZOJ 题解 对于每个值,维护一棵线段树就好啦 动态开点,否则空间开不下 剩下的就是很简单的问题啦 当然了 ...
- 【模板】exBSGS/Spoj3105 Mod
[模板]exBSGS/Spoj3105 Mod 题目描述 已知数\(a,p,b\),求满足\(a^x\equiv b \pmod p\)的最小自然数\(x\). 输入输出格式 输入格式: 每个测试文件 ...
- 【bzoj3238】 Ahoi2013—差异
http://www.lydsy.com/JudgeOnline/problem.php?id=3238 (题目链接) 题意 给出一个字符串,求${\sum_{1<=i<j<=n} ...
- 1.Qt简介
附件列表 1.Qt简介.png
- P4310 绝世好题
P4310 绝世好题 题目描述 给定一个长度为n的数列ai,求ai的子序列bi的最长长度,满足bi&bi-1!=0(2<=i<=len). 说明 对于100%的数据,1<=n ...
- [Java] I/O底层原理之一:字符流、字节流及其源码分析
关于 I/O 的类可以分为四种: 关于字节的操作:InputStream 和 OutPutStream: 关于字符的操作:Writer 和 Reader: 关于磁盘的操作:File: 关于网络的操作: ...
- 转:Block原理及引用循环问题
2010年WWDC发布iOS4时Apple对Objective-C进行了一次重要的升级:支持Block.说到底这东西就是闭包,其他高级语音例如Java和C++已有支持,第一次使用Block感觉满简单好 ...
- JS中双等号“==”使用情况
1.判断一个对象的值是否存在 var obj = {}; if(obj.a == null) { // todo } 2. 判断函数入参是否存在 function (a, b) { if(a == n ...
- 使用 Collections 实现排序 sort方法 对List 实体类实现Comparable类 示例
package com.test.jj; import java.util.ArrayList; import java.util.Collections; public class Test { A ...