Python协同(coroutines)类似于生成器,会使用yield关键字,但它不是生成数据,而是通常消费(consume)数据。
Exercise with coroutines
1. Create a coroutine named “square” that prints the square of any sent value.
def square():
print('square')
while True:
val = yield
print(val*val)
s=square()
next(s)
s.send(2)
s.send(3)
s.send(4)
s.close()
s.send(5)
2. Implement the “minimize” coroutine that keeps and prints the minimum value that is sent to the function.
def minimize():
print("minimize")
var = yield
min = var
print('min',min)
while True:
curr = yield
if min>=curr:
min=curr
print("min",min)
m = minimize()
next(m)
m.send(3)
m.send(2)
m.send(5)
Exercise with coroutines
1. Implement a producer-consumer pipeline where the values squared by the producer are sent to two consumers. One should store and print the minimum value sent so far and the other the maximum value.
def producer(consumers):
print('producer ready')
try:
while True:
var = yield
for consumer in consumers:
consumer.send(var*var)
except GeneratorExit:
for consumer in consumers:
consumer.close()
def consumer(name,func):
print(f"{name} ready")
var = yield
max = var
min = var
print(f"current {func} value is {var}")
try:
while True:
curr = yield
if func == "max":
if max<=curr:
max=curr
print(f"current max value is {max}")
else:
if min>=curr:
min=curr
print(f"current min value is {min}")
except GeneratorExit:
print(f"{name} closed")
conmax = consumer("conmax","max")
conmin = consumer("conmin","min")
proc = producer([conmax,conmin])
next(conmax)
next(conmin)
next(proc)
proc.send(1)
proc.send(2)
proc.send(5)
proc.send(0)
2. Implement a producer-consumer pipeline where the values squared by the producer are dispatched to two consumers, one at a time. The first value should be sent to consumer 1, the second value to consumer 2, third value to consumer 1 again, and so on. Closing the producer should force the consumers to print a list with the numbers that each one obtained.
def turn_on(label):
if label==1:
return 0
elif label==0:
return 1
def producer(consumers):
print("producer ready")
try:
index = 0
while True:
var = yield
consumers[index].send(var*var)
index = turn_on(index)
except GeneratorExit:
for consumer in consumers:
consumer.close()
list=[[] for i in range(2)]
def consumer(name,label):
print(f"{name} ready")
try:
while True:
var = yield
list[label].append(var)
print(f"consumer{label+1}",var)
except GeneratorExit:
print(f"consumer{label+1}",list[label])
con1 = consumer("consumer1",0)
con2 = consumer("consumer2",1)
prod = producer([con1,con2])
next(con1)
next(con2)
next(prod)
prod.send(1)
prod.send(2)
prod.send(3)
prod.send(4)
prod.close()