Python之Queue模块

Queue

1、创建一个“队列”对象

>>> import Queue
>>> queue = Queue.Queue(maxsize=100)
>>> queue.qsize()

Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。

class Queue
 |  Create a queue object with a given maximum size.
 |  
 |  If maxsize is <= 0, the queue size is infinite.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, maxsize=0)

2、将一个值放入队列中

>>> queue.put(10)
>>> queue.qsize()
1

调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。

 |  put(self, item, block=True, timeout=None)
 |      Put an item into the queue.
 |      
 |      If optional args 'block' is true and 'timeout' is None (the default),
 |      block if necessary until a free slot is available. If 'timeout' is
 |      a positive number, it blocks at most 'timeout' seconds and raises
 |      the Full exception if no free slot was available within that time.
 |      Otherwise ('block' is false), put an item on the queue if a free slot
 |      is immediately available, else raise the Full exception ('timeout'
 |      is ignored in that case).

3、将一个值从队列中取出

>>> queue.get()
10
>>> queue.qsize()
0
>>

调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。

4、python queue模块有三种队列

(1)、python queue模块的FIFO队列先进先出。
(2)、LIFO类似于堆。即先进后出。
(3)、还有一种是优先级队列级别越低越先出来。 

针对这三种队列分别有三个构造函数:
(1)、class Queue.Queue(maxsize) FIFO 
(2)、class Queue.LifoQueue(maxsize) LIFO ,类似stack栈
(3)、class Queue.PriorityQueue(maxsize) 优先级队列 

>>> import Queue
>>> priqueue = Queue.PriorityQueue()
>>> 
>>> priqueue.put((1,'a'))
>>> priqueue.put((2,'b'))
>>> priqueue.get()
(1, 'a')
值小的优先被获取,队列元素的格式为(priority_number, data)

介绍一下此包中的常用方法:

Queue.qsize() 返回队列的大小 
Queue.empty() 如果队列为空,返回True,反之False 
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应 
Queue.get([block[, timeout]]) 获取队列,timeout等待时间 
Queue.get_nowait() 相当Queue.get(False)
非阻塞 Queue.put(item) 写入队列,timeout等待时间 
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.task_done() 在完成一项工作之后,Queue.task_done() 函数向任务已经完成的队列发送一个信号

Queue.join() 实际上意味着等到队列为空,再执行别的操作

 例子1:

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

例子2:

#!/usr/bin/env python2.7
#-*-coding:utf-8 -*-

import Queue
import threading

f = open('test.log','w')

def lancher(i,q):
    while True:
        id = q.get()
        msg="id=%d
" % id
        print msg 

        q.task_done()

queue = Queue.Queue()

for i in range(5):
    worker = threading.Thread(target=lancher,args=(i,queue))
    worker.setDaemon(True)
    worker.start()                                                                                                           


for i in range(100):
    queue.put(i)
print "Queue size=%d" % queue.qsize()
queue.join()

f.close()
原文地址:https://www.cnblogs.com/gsblog/p/3615300.html