python优先队列使用_Python优先队列实现方法示例

本文通过实例代码介绍了Python中如何使用PriorityQueue实现优先队列,并结合多线程进行任务处理。文章展示了如何创建Job类来设置任务优先级,以及如何启动多个工作线程从队列中取出并处理任务。最后,给出了程序的执行结果。
摘要由CSDN通过智能技术生成

本文实例讲述了Python优先队列实现方法。分享给大家供大家参考,具体如下:

1. 代码

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,'Mid-level job'))

q.put(Job(10,'Low-level job'))

q.put(Job(1,'Important 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()

2. 执行结果

New job: Mid-level job

New job: Low-level job

New job: Important job

Processing job: Important job

Processing job: Mid-level job

Processing job: Low-level job

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

本文标题: Python优先队列实现方法示例

本文地址: http://www.cppcns.com/jiaoben/python/204579.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值