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. HDU 1711 Number Sequence (字符串匹配,KMP算法)

    HDU 1711 Number Sequence (字符串匹配,KMP算法) Description Given two sequences of numbers : a1, a2, ...... , ...

  2. 20170520 DP阶段总结

    DP的力量不是无穷的. 但是,因为它叫做“动态规划”,它在OI界如鱼得水.这个“动态”不是指“离线”与“在线”,也不是什么“可持久化”.它只是把问题抽象为一个个“阶段”,在每一个“阶段”中作出或繁或简 ...

  3. eclipse安装activiti5.18.0工作流插件 以及安装过程中activiti插件出现的问题及解决

    转: eclipse安装activiti5.18.0工作流插件 以及安装过程中activiti插件出现的问题及解决 2017年05月04日 18:44:21 JJ_nan 阅读数:2773   版权声 ...

  4. EndNote文献悬挂缩进的设置方法及设置参考文献序号后面空格长度

    一.EndNote文献悬挂缩进的设置方法 写论文时使用EndNote来插入和管理参考文献是一种非常方便的方法,但有时不同的杂志要求插入的文献要求第二行缩进格式,或者不缩进. 1.在EndNote中Ed ...

  5. 编译geth报错的解决方法 make: *** [geth] 错误 1

    在centos下安装了go1.9.1版本,编译go-ethereum时报错: [root@localhost go-ethereum]# make gethbuild/env.sh go run bu ...

  6. ElasticStack系列之六 & 版本冲突处理之乐观锁

    悲观并发控制(PCC) 这一点在关系数据库中被广泛使用.假设这种情况很容易发生,我们就可以阻止对这一资源的访问.典型的例子就是当我们在读取一个数据前先锁定这一行,然后确保只有读取到数据的这个线程可以修 ...

  7. CF916E Jamie and Tree

    CF916E Jamie and Tree 题意翻译 有一棵n个节点的有根树,标号为1-n,你需要维护以下三种操作 1.给定一个点v,将整颗树的根变为v 2.给定两个点u, v,将lca(u, v)所 ...

  8. Linux 下搭建 Svn+Apache

    一.安装apache 1.检查apache是否安装 rpm -qa|grep httpd 2.使用yum安装apache yum -y install httpd 3.记住安装的版本号 httpd.x ...

  9. Lena与数字图像处理

    在数字图像处理中,Lena(Lenna)是一张被广泛使用的标准图片,特别在图像压缩的算法研究中. 黑白Lena图   标准Lena (为什么用这幅图,是因为这图的各个频段的能量都很丰富:即有低频(光滑 ...

  10. [LeetCode] 329. Longest Increasing Path in a Matrix ☆☆☆

    Given an integer matrix, find the length of the longest increasing path. From each cell, you can eit ...