Last active
July 2, 2017 13:16
-
-
Save bwangelme/18ce63e28567f645e7e3ef8dee306dfa to your computer and use it in GitHub Desktop.
生产者消费者问题的Python协程实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment