码迷,mamicode.com
首页 > 其他好文 > 详细

每日一“酷”之Queue

时间:2014-10-19 14:20:59      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   ar   使用   for   

 

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

显示结果:

bubuko.com,布布扣

 

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

 

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

运行结果:

bubuko.com,布布扣

 

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()

运行结果:

bubuko.com,布布扣

 

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

 

每日一“酷”之Queue

标签:des   style   blog   http   color   io   ar   使用   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!