首页 > 编程语言 > 详细

多线程——生产者和消费者

时间:2015-11-02 17:11:37      阅读:277      评论:0      收藏:0      [点我收藏+]

生产者和消费者进程举例:

# producer_consumer_queue

from Queue import Queue

import random

import threading

import time

 

#Producer thread

class Producer(threading.Thread):

    def __init__(self, t_name, queue):

        threading.Thread.__init__(self, name=t_name)

        self.data=queue

    def run(self):

        for i in range(5):

            print "%s: %s is producing %d to the queue!/n" %(time.ctime(), self.getName(), i)

            self.data.put(i)

            time.sleep(random.randrange(10)/5)

        print "%s: %s finished!" %(time.ctime(), self.getName())

 

#Consumer thread

class Consumer(threading.Thread):

    def __init__(self, t_name, queue):

        threading.Thread.__init__(self, name=t_name)

        self.data=queue

    def run(self):

        for i in range(5):

            val = self.data.get()

            print "%s: %s is consuming. %d in the queue is consumed!/n" %(time.ctime(), self.getName(), val)

            time.sleep(random.randrange(10))

        print "%s: %s finished!" %(time.ctime(), self.getName())

 

#Main thread

def main():

    queue = Queue()

    producer = Producer(Pro., queue)

    consumer = Consumer(Con., queue)

    producer.start()

    consumer.start()

    producer.join()

    consumer.join()

    print All threads terminate!

 

if __name__ == __main__:

    main()

 

多线程——生产者和消费者

原文:http://www.cnblogs.com/myblog-lyc/p/4930598.html

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