queue

隊列,用於多線程之間安全的交換數據,queue.Queue模塊實現了全部必須的鎖定義。安全

FIFO:First Input First Output 先進先出多線程

LIFO:Last Input First Output 後進先出app

一、Queue (FIFO) 代碼示例:ide

 1 import queue
 2 import threading
 3 import time
 4 
 5 q = queue.Queue()
 6 threads = []
 7 queue_num = 5
 8 
 9 def worker():
10     while True:
11         data = q.get()
12         if data is None:
13             break
14         print('Get:', data)
15         q.task_done()    # 在get後調用,表示以前隊列的任務執行完成
16         time.sleep(1)
17 
18 for thread in range(2):
19     t = threading.Thread(target=worker)
20     t.start()
21     threads.append(t)
22 
23 for n in range(queue_num):
24     q.put('Item_%s' % n)
25     print('Put:', 'Item_%s' % n)
26 
27 q.join()    # 阻塞,直到隊列中的全部項都被獲取並處理
28 
29 for i in range(queue_num):
30     q.put(None)
31 
32 for t in threads:
33     t.join()
# 所有按順序獲取
Put: Item_0
Get: Item_0
Put: Item_1
Get: Item_1
Put: Item_2
Put: Item_3
Put: Item_4
Get: Item_2
Get: Item_3
Get: Item_4
FIFO 輸出結果

二、LifoQueue (LIFO) 代碼示例:spa

 1 # 和Queue同樣,只是在實例化時,將queue.Queue改成queue.LifoQueue
 2 
 3 import queue
 4 import threading
 5 import time
 6 
 7 q = queue.LifoQueue(maxsize=3)    # 後進先出隊列,隊列上限爲3
 8 threads = []
 9 queue_num = 5
10 
11 def worker():
12     while True:
13         data = q.get()
14         if data is None:
15             break
16         print('Get:', data)
17         q.task_done()
18         time.sleep(1)
19 
20 for thread in range(2):
21     t = threading.Thread(target=worker)
22     t.start()
23     threads.append(t)
24 
25 for n in range(queue_num):
26     q.put('Item_%s' % n)
27     print('Put:', 'Item_%s' % n)
28 
29 q.join()
30 
31 for i in range(queue_num):
32     q.put(None)
33 
34 for t in threads:
35     t.join()
Put: Item_0
Get: Item_0
Put: Item_1
Get: Item_1
Put: Item_2
Put: Item_3
Put: Item_4
Get: Item_4    # 後進先出
Get: Item_3
Get: Item_2
LIFO 輸出結果

 三、PriorityQueue : 優先級,put的數據爲一個元組:(優先級, 數據),數字越低優先級越高,越先被get方法獲取,代碼示例:線程

 1 import queue
 2 import threading
 3 import time
 4 
 5 q = queue.PriorityQueue()
 6 threads = []
 7 queue_num = 5
 8 
 9 def worker():
10     while True:
11         data = q.get()
12         if data[1] is None:
13             break
14         print('Get:', data)
15         q.task_done()
16         time.sleep(1)
17 
18 for thread in range(2):
19     t = threading.Thread(target=worker)
20     t.start()
21     threads.append(t)
22 
23 for n in range(queue_num):
24     q.put((n, 'Item_%s' % n))
25     print('Put:', 'Item_%s' % n)
26 
27 q.join()
28 
29 for i in range(queue_num):
30     q.put((0, None))
31 
32 for t in threads:
33     t.join()
Put: Item_0
Get: (0, 'Item_0')
Put: Item_1
Get: (1, 'Item_1')
Put: Item_2
Put: Item_3
Put: Item_4
Get: (2, 'Item_2')    # 數字越小,越先被get獲取
Get: (3, 'Item_3')
Get: (4, 'Item_4')
PriorityQueue 輸出結果
相關文章
相關標籤/搜索