Python 中的Queue实现了经典的先入先出队列,并且是线程安全的。同时在此基础上还提供了其它许多高级功能。我们先从经典的先入先出FIFO队列开始,看下面的代码:
import Queue
q=Queue.Queue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get(),
其输出结果为:0 1 2 3 4
可见这是一个标准的先入先出队列。此外,Python还实现了后人先出LIFO队列,我们只要使用Queue的LifoQueue对象就可以完成,比如下面的代码:
import Queue
q=Queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get(),
其输出结果为:4 3 2 1 0
除此之外,我们还可以自定义队列的排列顺序,比如有时候我们可能需要根据对象中的某个字段来排序,那么我们可以使用Queue的PriorityQueue。当然我们还要做一些额外的工作,告诉PriorityQueue,我们要使用哪个字段进行排序,比如下面的代码中我们通过实现对象的__cmp__方法告诉PriorityQueue我们要用priority字段进行排序:
import Queue
import threading
class Job(object):
def __init__(self,priority,description):
self.priority=priority
self.description=description
print 'New Job:',description
return
def __cmp__(self, other):
return cmp(self.priority,other.priority)
q=Queue.PriorityQueue()
q.put(Job(3,'Middle Level Job.'))
q.put(Job(10,'Low Level Job.'))
q.put(Job(1,'High Level Job.'))
def process_job(q):
while True:
next_job=q.get()
print 'processing job:',next_job.description
q.task_done()
workers=[threading.Thread(target=process_job,args=(q,)),
threading.Thread(target=process_job,args=(q,)),]
for w in workers:
w.setDaemon(True)
w.start()
q.join()
其输出结果为:
New Job: Middle Level Job.
New Job: Low Level Job.
New Job: High Level Job.
processing job: High Level Job.
processing job: Middle Level Job.
processing job: Low Level Job.
可以看到,虽然我们并没有按照priority的顺序将对象压入队列,但是队列的排序还是按照priority输出的,这就是因为我们使用了PriorityQueue对象。
转自:http://www.onepub.net/2011/08/24/queue-%E9%98%9F%E5%88%97%E7%9A%84%E4%BD%BF%E7%94%A8/