首页 > 编程语言 > 详细

Python实现:生产者消费者模型(Producer Consumer Model)

时间:2018-01-09 12:39:38      阅读:299      评论:0      收藏:0      [点我收藏+]
#!/usr/bin/env python
#encoding:utf8

from Queue import Queue
import random,threading,time

#生产者类
class Producer(threading.Thread):
    def __init__(self, name,queue):
        threading.Thread.__init__(self, name=name)
        self.data=queue

    def run(self):
        for i in range(5):
            print("%s is producing %d to the queue!" % (self.getName(), i))
            self.data.put(i)
            time.sleep(random.randrange(10)/5)
        print("%s finished!" % self.getName())

#消费者类
class Consumer(threading.Thread):
    def __init__(self,name,queue):
        threading.Thread.__init__(self,name=name)
        self.data=queue
    def run(self):
        for i in range(5):
            val = self.data.get()
            print("%s is consuming. %d in the queue is consumed!" % (self.getName(),val))
            time.sleep(random.randrange(10))
        print("%s finished!" % self.getName())

def main():
    queue = Queue()
    producer = Producer(Producer,queue)
    consumer = Consumer(Consumer,queue)

    producer.start()
    consumer.start()

    #producer.join()
    #consumer.join()
    print All threads finished!

if __name__ == __main__:
    main()

 

Python实现:生产者消费者模型(Producer Consumer Model)

原文:https://www.cnblogs.com/djoker/p/8250751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!