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

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

时间:2018-01-09 12:58:34      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:模型   join   join()   mod   get   消费者   rod   min   range   

#!/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)

标签:模型   join   join()   mod   get   消费者   rod   min   range   

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

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