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(): 实际上意味着等到队列为空,再执行别的操作
例子:
#!/usr/bin/env python # -*- coding:utf-8 -*- # @time: 2017/12/18 19:31 # Author: caicai # @File: demon3.py '''写一个消费者和生产者,为了练习多线程,用多线程的方式实现,并通过类的重写的方法来实现''' from Queue import Queue from threading import Thread import time #生成类,输出一堆数字 class Proceduer(Thread): def __init__(self,queue): super(Proceduer, self).__init__() self.queue = queue def run(self): try: for i in xrange(1,10): print("put data is: {0} to queue".format(i)) self.queue.put(i) except Exception as e: print("put data error!") raise e #消费者类 class Consumer_odd(Thread): def __init__(self,queue): super(Consumer_odd, self).__init__() self.queue = queue def run(self): try: while not self.queue.empty(): number = self.queue.get() if number % 2 != 0: print("get {0} from queue ODD".format(number)) else: self.queue.put(number) time.sleep(1) except Exception as e: raise e class Consumer_even(Thread): def __init__(self,queue): super(Consumer_even, self).__init__() self.queue = queue def run(self): try: while not self.queue.empty(): #queue.empty() number = self.queue.get() if number % 2 == 0: print("get {0} from queue EVEN,thread name is: {1}".format(number, self.getName())) else: self.queue.put(number) time.sleep(1) except Exception as e: raise e def main(): queue = Queue() p = Proceduer(queue=queue) p.start() p.join() time.sleep(1) c1 = Consumer_odd(queue=queue) c2 = Consumer_even(queue=queue) c1.start() c2.start() c1.join() c2.join() print("All threads terminate!") if __name__ == '__main__': main() 输出结果: put data is: 1 to queue put data is: 2 to queue put data is: 3 to queue put data is: 4 to queue put data is: 5 to queue put data is: 6 to queue put data is: 7 to queue put data is: 8 to queue put data is: 9 to queue get 1 from queue ODD get 2 from queue EVEN,thread name is: Thread-3 get 5 from queue ODD get 6 from queue EVEN,thread name is: Thread-3 get 7 from queue ODD get 8 from queue EVEN,thread name is: Thread-3 get 9 from queue ODD get 4 from queue EVEN,thread name is: Thread-3get 3 from queue ODD All threads terminate!