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)的更多相关文章

  1. Python并发编程协程(Coroutine)之Gevent

    Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporate routine的缩写,直接翻译 ...

  2. Python 协程 (Coroutine)

    协程 (Coroutine) 什么是协程 协程(微线程)是比线程更轻量化的存在,像一个进程可以拥有多个线程一样,一个线程也可以拥有多个协程 最重要的是,协程不是被操作系统内核所管理,而完全是由程序所控 ...

  3. 操作系统OS,Python - 协程(Coroutine)

    留坑 参考: https://en.wikipedia.org/wiki/Coroutine https://zh.wikipedia.org/wiki/%E5%8D%8F%E7%A8%8B http ...

  4. (zt)Lua的多任务机制——协程(coroutine)

    原帖:http://blog.csdn.net/soloist/article/details/329381 并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上 ...

  5. 协程coroutine

    协程(coroutine)顾名思义就是“协作的例程”(co-operative routines).跟具有操作系统概念的线程不一样,协程是在用户空间利用程序语言的语法语义就能实现逻辑上类似多任务的编程 ...

  6. Lua的多任务机制——协程(coroutine)

    并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上有这么两种多任务技术,一种是抢占式多任务(preemptive multitasking),它让操作系统来决定 ...

  7. 深入理解Python中协程的应用机制: 使用纯Python来实现一个操作系统吧!!

    本文参考:http://www.dabeaz.com/coroutines/   作者:David Beazley 缘起: 本人最近在学习python的协程.偶然发现了David Beazley的co ...

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

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

  9. 关于Python的协程问题总结

    协程其实就是可以由程序自主控制的线程 在python里主要由yield 和yield from 控制,可以通过生成者消费者例子来理解协程 利用yield from 向生成器(协程)传送数据# 传统的生 ...

随机推荐

  1. Machine Learning CodeForces - 940F(带修改的莫队)

    题解原文地址:https://www.cnblogs.com/lujiaju6555/p/8468709.html 给数组a,有两种操作,1 l r查询[l,r]中每个数出现次数的mex,注意是出现次 ...

  2. MT【156】特例$a_n=\dfrac{6}{\pi n^2}$

    设无穷非负数列$\{a_n\}$满足$a_n+a_{n+2}\ge2 a_{n+1},\sum\limits_{i=1}^{n}{a_i}\le1$,证明:$0\le a_n-a_{n+1}\le\d ...

  3. UOJ #126 【NOI2013】 快餐店

    题目链接:快餐店 震惊!某ZZ选手此题调了一天竟是因为……>>点击查看 一般碰到这种基环树的题都要先想想树上怎么做.这道题如果是在树上的话……好像求一遍直径就做完了?答案就是直径长度的一半 ...

  4. POJ.1330 Nearest Common Ancestors (LCA 倍增)

    POJ.1330 Nearest Common Ancestors (LCA 倍增) 题意分析 给出一棵树,树上有n个点(n-1)条边,n-1个父子的边的关系a-b.接下来给出xy,求出xy的lca节 ...

  5. Jenkins(二)---jenkins之Git+maven+jdk+tomcat

    git+maven+jdk+tomcat  这四个软件可以百度在linux下的安装,不再赘述. server A --->   jenkins主机ip:192.168.100.119 serve ...

  6. Struts2的配置文件中, <package>的作用,<action><result>重名?

    问:Struts2的配置文件中, <package>的作用是什么? 答:防止action重名啊,例如前台和后台,总会有很多地方起名重复的! 问:可是访问的时候,不也是访问action吗,能 ...

  7. TIME_WAIT状态的一些总结

    前言: TCP断开连接的四次握手中, 主动关闭连接的一方的TIME_WAIT状态尤为重要. 1:TCP连接的三次握手和断开的四次挥手 2:由上图可知 在主动关闭的一方, 会经历TIME_WAIT状态, ...

  8. Python高手之路【四】python函数装饰器,迭代器

    def outer(func): def inner(): print('hello') print('hello') print('hello') r = func() print('end') p ...

  9. day4 数组学习

    java提供的数组排序操作:java.util.Arrays.sort(数组名): java提供的数组复制:system.arraycopy(源数组名称,源数组开始点下标,目标数组名称,目标数组开始下 ...

  10. day3 程序流程控制

    今天主要学习了while和do/while,以及运用循环做一些小的练习. 学习了如何断点调试程序. 程序设计的步骤: 1.分析问题 2.确定数据结构和算法 3.编制程序 4.调试问题