# 使用yield生成器实现协程
# 协程:没有上下文切换开销,访问资源加锁问题
# 但不能从分利用多核
def consumer():
res = ""
while True:
n = yield res # 将res返回给send返回值,并阻塞等待下次send命令
if n is None:
return
print("consumer: {}".format(n))
res = "consumer:{}, ok".format(n)
def producter(c):
c.send(None) # 预处理, yield进行阻塞
n = 0
while n < 5:
n = n + 1
print("producter: {}".format(n))
# 开始执行yield之后语句,并将数据n传递给yield赋值变量n,生成器往下执行直到
# yield将res返回给res变量
res = c.send(n)
print("consumer res:{}".format(res))
c = consumer()
producter(c)
# producter: 1
# consumer: 1
# consumer res:consumer:1, ok
# producter: 2
# consumer: 2
# consumer res:consumer:2, ok
# producter: 3
# consumer: 3
# consumer res:consumer:3, ok
# producter: 4
# consumer: 4
# consumer res:consumer:4, ok
# producter: 5
# consumer: 5
# consumer res:consumer:5, ok