python中的Queue模塊


queue介紹

  • queue是python的標准庫,俗稱隊列.可以直接import引用,在python2.x中,模塊名為Queue。python3直接queue即可
  • 在python中,多個線程之間的數據是共享的,多個線程進行數據交換的時候,不能夠保證數據的安全性和一致性,所以當多個線程需要進行數據交換的時候,隊列就出現了,隊列可以完美解決線程間的數據交換,保證線程間數據的安全性和一致性(簡單的來說就是多線程需要加鎖,很可能會造成死鎖,而queue自帶鎖。所以多線程結合queue會好的很多。案例:https://www.cnblogs.com/nul1/p/9901942.html)

queue模塊有三種隊列及構造函數:

  1. Python queue模塊的FIFO隊列先進先出。 class queue.Queue(maxsize)
  2. LIFO類似於堆,即先進后出。 class queue.LifoQueue(maxsize)
  3. 還有一種是優先級隊列級別越低越先出來。 class queue.PriorityQueue(maxsize)

一:FIFO先進先出

  FIFO即First in First Out,先進先出。Queue提供了一個基本的FIFO容器,使用方法很簡單,maxsize是個整數,指明了隊列中能存放的數據個數的上限。一旦達到上限,插入會導致阻塞,直到隊列中的數據被消費掉。如果maxsize小於或者等於0,隊列大小沒有限制。

1 import Queue
2 q = Queue.Queue()
3 for i in range(5):
4     q.put(i)
5 while not q.empty():
6     print q.get()

輸出:

0 1 2 3 4

二:LIFO先進先出

  LIFO即Last in First Out,后進先出。與棧的類似,使用也很簡單,maxsize用法同上

1 import Queue
2 
3 q = Queue.LifoQueue()
4 
5 for i in range(5):
6     q.put(i)
7 
8 while not q.empty():
9     print q.get()
View Code

輸出:

4
3
2
1 0

三:優先級隊列

class Queue.PriorityQueue(maxsize=0)

構造一個優先隊列。maxsize用法同上。

 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 'Job:',description
 9         return
10     def __cmp__(self, other):
11         return cmp(self.priority, other.priority)
12 
13 q = Queue.PriorityQueue()
14 
15 q.put(Job(3, 'level 3 job'))
16 q.put(Job(10, 'level 10 job'))
17 q.put(Job(1, 'level 1 job'))
18 
19 def process_job(q):
20     while True:
21         next_job = q.get()
22         print 'for:', next_job.description
23         q.task_done()
24 
25 workers = [threading.Thread(target=process_job, args=(q,)),
26         threading.Thread(target=process_job, args=(q,))
27         ]
28 
29 for w in workers:
30     w.setDaemon(True)
31     w.start()
32 
33 q.join()
View Code
Job: level 3 job Job: level 10 job Job: level 1 job for: level 1 job for: level 3 job for: level 10 job

queue模塊中的常用方法:

  • queue.qsize() 返回隊列的大小
  • queue.empty() 如果隊列為空,返回True,反之False
  • queue.full() 如果隊列滿了,返回True,反之False
  • queue.full 與 maxsize 大小對應
  • queue.get([block[, timeout]])獲取隊列,timeout等待時間
  • queue.get_nowait() 相當queue.get(False)
  • queue.put(item) 寫入隊列,timeout等待時間
  • queue.put_nowait(item) 相當queue.put(item, False)
  • queue.task_done() 在完成一項工作之后,queue.task_done()函數向任務已經完成的隊列發送一個信號
  • queue.join() 實際上意味着等到隊列為空,再執行別的操作

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM