Queue 队列的使用

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值