Python提供了Queue模块来专门实现消息队列Queue对象
Queue对象实现一个fifo队列(其他的还有lifo、priority队列,这里不再介绍)。queue只有maxsize一个构造参数,用来指定队列容量,指定为0的时候代表容量无限。主要有以下成员函数:
Queue.qsize():返回消息队列的当前空间。返回的值不一定可靠。
Queue.empty():判断消息队列是否为空,返回True或False。同样不可靠。
Queue.full():类似上边,判断消息队列是否满
Queue.put(item, block=True, timeout=None):往消息队列中存放消息。block可以控制是否阻塞,timeout指定阻塞时候的等待时间。如果不阻塞或者超时,会引起一个full exception。
Queue.put_nowait(item):相当于put(item, False).
Queue.get(block=True, timeout=None):获取一个消息,其他同put。
以下两个函数用来判断消息对应的任务是否完成。
Queue.task_done():接受消息的线程通过调用这个函数来说明消息对应的任务已完成。
Queue.join(): 实际上意味着等到队列为空,再执行别的操作
例子:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # @time: 2017/12/18 19:31 4 # Author: caicai 5 # @File: demon3.py 6 7 '''写一个消费者和生产者,为了练习多线程,用多线程的方式实现,并通过类的重写的方法来实现''' 8 from Queue import Queue 9 from threading import Thread 10 import time 11 12 #生成类,输出一堆数字 13 class Proceduer(Thread): 14 def __init__(self,queue): 15 super(Proceduer, self).__init__() 16 self.queue = queue 17 def run(self): 18 try: 19 for i in xrange(1,10): 20 print("put data is: {0} to queue".format(i)) 21 self.queue.put(i) 22 23 except Exception as e: 24 print("put data error!") 25 raise e 26 27 #消费者类 28 class Consumer_odd(Thread): 29 def __init__(self,queue): 30 super(Consumer_odd, self).__init__() 31 self.queue = queue 32 def run(self): 33 try: 34 while not self.queue.empty(): 35 number = self.queue.get() 36 if number % 2 != 0: 37 print("get {0} from queue ODD".format(number)) 38 else: 39 self.queue.put(number) 40 time.sleep(1) 41 except Exception as e: 42 raise e 43 44 class Consumer_even(Thread): 45 def __init__(self,queue): 46 super(Consumer_even, self).__init__() 47 self.queue = queue 48 def run(self): 49 try: 50 while not self.queue.empty(): #queue.empty() 51 number = self.queue.get() 52 if number % 2 == 0: 53 print("get {0} from queue EVEN,thread name is: {1}".format(number, self.getName())) 54 else: 55 self.queue.put(number) 56 time.sleep(1) 57 except Exception as e: 58 raise e 59 60 def main(): 61 queue = Queue() 62 63 p = Proceduer(queue=queue) 64 p.start() 65 p.join() 66 time.sleep(1) 67 c1 = Consumer_odd(queue=queue) 68 c2 = Consumer_even(queue=queue) 69 c1.start() 70 c2.start() 71 c1.join() 72 c2.join() 73 74 print("All threads terminate!") 75 76 if __name__ == '__main__': 77 main() 78 79 输出结果: 80 81 put data is: 1 to queue 82 put data is: 2 to queue 83 put data is: 3 to queue 84 put data is: 4 to queue 85 put data is: 5 to queue 86 put data is: 6 to queue 87 put data is: 7 to queue 88 put data is: 8 to queue 89 put data is: 9 to queue 90 get 1 from queue ODD 91 get 2 from queue EVEN,thread name is: Thread-3 92 get 5 from queue ODD 93 get 6 from queue EVEN,thread name is: Thread-3 94 get 7 from queue ODD 95 get 8 from queue EVEN,thread name is: Thread-3 96 get 9 from queue ODD 97 get 4 from queue EVEN,thread name is: Thread-3get 3 from queue ODD 98 99 All threads terminate!