每日一“酷”之Queue

Queue—线程安全的FIFO实现

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

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

1、  基本FIFO队列

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

 1 import Queue
 2 
 3 q = Queue.LifoQueue()
 4 a= range(5)
 5 print u'正序列表:',a
 6 for i in a:
 7     q.put(i)
 8 print u'移除队列序列:'
 9 while not q.empty():
10     print q.get(),
11 print
12 
13 a= range(5)
14 a.sort(reverse=True)
15 print u'逆序列表:',a
16 for i in a:
17     q.put(i)
18 print u'移除队列序列:'
19 while not q.empty():
20     print q.get(),
21 print

显示结果:

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

2、  LIFO队列

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

 1 import Queue
 2 
 3 q = Queue.Queue()
 4 a= range(5)
 5 print u'正序列表:',a
 6 for i in a:
 7     q.put(i)
 8 print u'移除队列顺序:'
 9 while not q.empty():
10     print q.get(),
11 print
12 
13 a= range(5)
14 a.sort(reverse=True)
15 print u'逆序列表:',a
16 for i in a:
17     q.put(i)
18 print u'移除队列顺序:'
19 while not q.empty():
20     print q.get(),
21 print

运行结果:

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

task_cone()

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

Join()

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

3、  优先队列

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

 1 import Queue
 2 import threading
 3 
 4 class Job(object):
 5     def __init__(self,priority,description):
 6         self.priority = priority
 7         self.description = description
 8         print 'New job:',description
 9         return 
10     def __cmp__(self,other):
11 #         print 'a:',self.priority
12 #         print 'b:',other.priority
13 #         print cmp(self.priority,other.priority)
14         return cmp(self.priority,other.priority)
15 
16 
17 q = Queue.PriorityQueue()
18 q.put(Job(3,'Mid-level job'))
19 q.put(Job(10,'Low-level job'))
20 q.put(Job(1,'Important job'))
21 
22 def process_job(q):
23     while True:
24         next_job = q.get()
25         print 'Processing job:',next_job.description
26         q.task_done()
27  
28 workers = [threading.Thread(target = process_job,args = (q,)),
29            threading.Thread(target = process_job,args = (q,)),
30            ]
31 for w in workers:
32     w.setDaemon(True)
33     w.start()
34 q.join()

运行结果:

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

 

原文地址:https://www.cnblogs.com/victroy/p/4034611.html