码迷,mamicode.com
首页 > 编程语言 > 详细

Python生产者消费者模型

时间:2017-12-22 00:36:10      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:log   线程   生产者   多线程   队列   art   def   get   pos   

用多线程和队列来实现生产者消费者模型

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import queue
import time

q = queue.Queue()

def Producer(name):
    count = 1
    while True:
        q.put("面包%s" %count)
        print("[%s]做了[%s]个面包" %(name,count))
        count +=1
        time.sleep(1)

def Consumer(name):
    while True:
        print("[%s]取得[%s]并吃了它" %(name,q.get()))
        time.sleep(1)

t1 = threading.Thread(target=Producer,args=("掌柜",))
t2 = threading.Thread(target=Consumer,args=("张三",))
t3 = threading.Thread(target=Consumer,args=("李四",))

t1.start()
t2.start()
t3.start()

 运行结果

技术分享图片

生产一个消费一个,两个消费者是按照顺序一个一个地消费

Python生产者消费者模型

标签:log   线程   生产者   多线程   队列   art   def   get   pos   

原文地址:http://www.cnblogs.com/sch01ar/p/8082747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!