您可以将生成器变成协程,这样它们就可以send()
并互相接收值(使用(yield)
表达式)。这将使每个人都有机会更改他们收到的值,和/或将它们传递到下一个生成器/协程(或完全忽略它们)。
请注意,在下面的示例代码中,我使用了一个名为coroutine
“启动”生成器/协程函数。这使得它们在第一次执行之前就执行yield
表达/陈述。这是 YouTube 视频中的一个稍加修改的版本,该视频是一个非常有启发性的演讲,标题为关于协程和并发的有趣课程 https://www.youtube.com/watch?v=Z_OAlIhXziw这是 Dave Beazley 在 PyCon 2009 上发表的。
正如您应该能够从生成的输出中看到的,数据值正在由通过单个配置的每个管道进行处理send()
到头部协程,然后头部协程有效地将其“复用”到每个管道中。由于每个子协程也执行此操作,因此可以建立一个复杂的进程“树”。
import sys
def coroutine(func):
""" Decorator to "prime" generators used as coroutines. """
def start(*args,**kwargs):
cr = func(*args,**kwargs) # Create coroutine generator function.
next(cr) # Advance to just before its first yield.
return cr
return start
def pipe(name, value, divisor, coroutines):
""" Utility function to send values to list of coroutines. """
print(' {}: {} is divisible by {}'.format(name, value, divisor))
for cr in coroutines:
cr.send(value)
def this_func_name():
""" Helper function that returns name of function calling it. """
frame = sys._getframe(1)
return frame.f_code.co_name
@coroutine
def gen1(*coroutines):
while True:
value = (yield) # Receive values sent here via "send()".
if value % 2 == 0: # Only pipe even values.
pipe(this_func_name(), value, 2, coroutines)
@coroutine
def gen2(*coroutines):
while True:
value = (yield) # Receive values sent here via "send()".
if value % 4 == 0: # Only pipe values divisible by 4.
pipe(this_func_name(), value, 4, coroutines)
@coroutine
def gen3(*coroutines):
while True:
value = (yield) # Receive values sent here via "send()".
if value % 6 == 0: # Only pipe values divisible by 6.
pipe(this_func_name(), value, 6, coroutines)
# Create and link together some coroutine pipelines.
g3 = gen3()
g2 = gen2()
g1 = gen1(g2, g3)
# Send values through both pipelines (g1 -> g2, and g1 -> g3) of coroutines.
for value in range(17):
print('piping {}'.format(value))
g1.send(value)
Output:
piping 0
gen1: 0 is divisible by 2
gen2: 0 is divisible by 4
gen3: 0 is divisible by 6
piping 1
piping 2
gen1: 2 is divisible by 2
piping 3
piping 4
gen1: 4 is divisible by 2
gen2: 4 is divisible by 4
piping 5
piping 6
gen1: 6 is divisible by 2
gen3: 6 is divisible by 6
piping 7
piping 8
gen1: 8 is divisible by 2
gen2: 8 is divisible by 4
piping 9
piping 10
gen1: 10 is divisible by 2
piping 11
piping 12
gen1: 12 is divisible by 2
gen2: 12 is divisible by 4
gen3: 12 is divisible by 6
piping 13
piping 14
gen1: 14 is divisible by 2
piping 15
piping 16
gen1: 16 is divisible by 2
gen2: 16 is divisible by 4