python 归纳 (十四)_队列Queue实现生产者消费者
Posted sunzebo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 归纳 (十四)_队列Queue实现生产者消费者相关的知识,希望对你有一定的参考价值。
# -*- coding: UTF-8 -*- """ 多线程的生产者,消费者 使用队列Queue """ import Queue import threading import time import random queue = Queue.Queue(3) # 创建3个大小的队列 class Producer(threading.Thread): """ 生产者,往队列中写数据 """ def __init__(self, queue): super(Producer, self).__init__() # 调用父类构造函数 self.queue = queue def run(self): while True: my_rand_double = random.random() self.queue.put(my_rand_double) # 往队列写数据 print "producer randonm %f " % (my_rand_double) time.sleep(2) class Consumer(threading.Thread): """ 消费者,从队列中读取数据 """ def __init__(self, queue): super(Consumer, self).__init__() self.queue = queue def run(self): while True: my_data = self.queue.get() # 从队列读数据 print "consumer:",my_data," " time.sleep(1) if __name__ == ‘__main__‘: print "begin.... " # 启动线程 Producer(queue).start() Consumer(queue).start() Consumer(queue).start() print "main end.... " """ Out: begin.... producer randonm 0.321120 consumer: 0.32111958348 main end.... producer randonm 0.340942 consumer: 0.340942161065 producer randonm 0.672640 consumer: 0.672639677729 producer randonm 0.940307 consumer: 0.940307007999 producer randonm 0.497011 consumer: 0.497011018834 """
以上是关于python 归纳 (十四)_队列Queue实现生产者消费者的主要内容,如果未能解决你的问题,请参考以下文章