每日一“酷”之Queue

时间:2023-12-23 15:27:14

Queue—线程安全的FIFO实现

作用:提供一个线程安全的FIFO实现

Queue模块提供了一个适用于多线程编程的先进先出(first-in,first-out)数据结构,可以用来在生产者和消费者线程之间安全地传递消息或其他数据。它会为调用者处理锁定,使多个线程可以安全第处理同一个Queue实例。Queue的大小(其中包含的元素个数)可能要受限制,,以限制内存使用或处理。

1、  基本FIFO队列

Queue类实现一个基本不能的先进先出容器。使用put()将元素增加到序列一段,使用get()从另一端删除。

 import Queue

 q = Queue.LifoQueue()
a= range(5)
print u'正序列表:',a
for i in a:
q.put(i)
print u'移除队列序列:'
while not q.empty():
print q.get(),
print a= range(5)
a.sort(reverse=True)
print u'逆序列表:',a
for i in a:
q.put(i)
print u'移除队列序列:'
while not q.empty():
print q.get(),
print

显示结果:

每日一“酷”之Queue

这个例子使用一个线程,来展示按元素的插入顺序从队列删除元素。

2、  LIFO队列

与Queue的标准FIFO实现相反,LifoQueue使用了后进先出(last-in,first-out,LIFO)顺序(通常与栈数据结构关联)。

 import Queue

 q = Queue.Queue()
a= range(5)
print u'正序列表:',a
for i in a:
q.put(i)
print u'移除队列顺序:'
while not q.empty():
print q.get(),
print a= range(5)
a.sort(reverse=True)
print u'逆序列表:',a
for i in a:
q.put(i)
print u'移除队列顺序:'
while not q.empty():
print q.get(),
print

运行结果:

每日一“酷”之Queue

get将删除最近使用put插入到队列的元素。

task_cone()

在完成一项工作之后,Queue.task_done() 函数向任务已经完成的队列发送一个信号

Join()

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

3、  优先队列

有些情况下,队列中元素的处理顺序需要根据这些元素的特殊性来决定,而不只是在队列中创建或插入的顺序。例如:财务部门的打印作业可以能要优先于一个开发人员打印的代码清单。PriorityQueue使用队列内容有序顺序来决定获取哪一个元素。

 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):
# print 'a:',self.priority
# print 'b:',other.priority
# print cmp(self.priority,other.priority)
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()

运行结果:

每日一“酷”之Queue

这个例子有个多线程处理作业,要根据get()时队列中元素的优先级来处理。运行消费者线程时,增加到队列中的元素的处理顺序决定于线程上下文切换。