Queue是python标准库中的线程安全的队列(FIFO)实现,提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递
Queue对象实现一个fifo队列。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(): 实际上意味着等到队列为空,再执行别的操作
例子:
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(block=True,timeout=5) 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(): number = self.queue.get(block=True,timeout=5) 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() print queue p = Proceduer(queue=queue) print p 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 terminate!") if __name__ == '__main__': main()
运行结果:
<Queue.Queue instance at 0x0000000002B02EC8> <Proceduer(Thread-1, initial)> 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 9 from queue ODD get 4 from queue EVEN ,thread name is: Thread-3 get 7 from queue ODD get 8 from queue EVEN ,thread name is: Thread-3 get 3 from queue ODD all terminate!