Python使用生成器实现生产者消费者模式

import threading
import time

# 消费者
def consumer():
    data = ''
    while True:
        r = yield data
        data = '生产的'+r+'还不错'
        time.sleep(1)

# 生产者
def produce(con):
    con.send(None)
    for i in range(5):
        print('生产者生产了%d' % i)
        r = con.send(str(i))
        print(r)

m = consumer()
produce(m)

你可能感兴趣的:(Python使用生成器实现生产者消费者模式)