生产者消费者问题的Python协程实现
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import random
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s -- %(filename)s:%(lineno)d [%(message)s]',
stream=sys.stdout,
)
def get_item():
item = random.sample(range(1, 10), 3)
return item
def Consume():
while True:
item = yield
logging.debug('Getting %s' % (item))
def Produce(consumer):
while True:
item = get_item()
logging.debug('Producing %s' % (item))
consumer.send(item)
if __name__ == '__main__':
consumer = Consume()
# 这里next的含义时首先要运行到第一个yield,也可以使用consumer.send(None)
next(consumer)
producer = Produce(consumer)
next(producer)