掌握線程queue的三種用法
本節時長需控制在5分鐘內
queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.
有三種不同的用法
class queue.Queue(maxsize=0) #隊列:先進先出
import queue
q=queue.Queue()
q.put('first')
q.put('second')
q.put('third')
print(q.get())
print(q.get())
print(q.get())
'''
結果(先進先出):
first
second
third
'''
class queue.LifoQueue(maxsize=0) #堆棧:last in fisrt out
import queue
q=queue.LifoQueue()
q.put('first')
q.put('second')
q.put('third')
print(q.get())
print(q.get())
print(q.get())
'''
結果(後進先出):
third
second
first
'''
class queue.PriorityQueue(maxsize=0) #優先級隊列:存儲數據時可設置優先級的隊列
import queue
q=queue.PriorityQueue()
#put進入一個元組,元組的第一個元素是優先級(通常是數字,也可以是非數字之間的比較),數字越小優先級越高
q.put((20,'a'))
q.put((10,'b'))
q.put((30,'c'))
print(q.get())
print(q.get())
print(q.get())
'''
結果(數字越小優先級越高,優先級高的優先出隊):
(10, 'b')
(20, 'a')
(30, 'c')
'''