生产者以及消费者模式

code
import time
import random
from multiprocessing import Queue
 
# 生产者
def producer(q, num):
    for i in range(1, num + 1):
        food = 'Spam-%d' % i
        # time.sleep(random.uniform(1, 2))
        timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print('时间:%s\t生产者:%d 生产了 %d' % (timeVal, i, i))
        q.put(food)
 
# 消费者
def consumer(q):
    while True:
        food = q.get()
        if not food:
            break
        # time.sleep(random.uniform(1, 2))
        timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        time.sleep(1)
        print('时间:%s\t消费者吃了 %s' % (timeVal, food))
 
if __name__ == '__main__':
    q = Queue()
    num = 50
    # 生产者
    producer(q, num)
    q.put(None)
    # 消费者
    consumer(q)
 
    print('end') 

 

 
 
 
 
 
 
 
 
 
 

posted @ 2020-12-26 16:40  anobscureretreat  阅读(70)  评论(0编辑  收藏  举报