queue模塊提供了一個多線程安全的先進先出FIFO(first in first out)的數據結構。
1.基本使用
put()放入元素,get()取出元素。
import queue
q = queue.Queue()
for i in range(5):
q.put(i)
# 驗證隊列是否為空
while not q.empty():
print(q.get(), end=" ")
輸出:
0 1 2 3 4
2.LIFO隊列
與FIFO相反,LIFO是后進后出。
import queue
q = queue.LifoQueue()
for i in range(5):
q.put(i)
# 驗證隊列是否為空
while not q.empty():
print(q.get(), end=" ")
結果:
4 3 2 1 0
3.優先隊列
根據元素的特性來決定這些元素的處理順序。
import queue
import functools
import threading
@functools.total_ordering
class Job:
def __init__(self, priority, description):
self.priority = priority
self.description = description
print("New job:", description)
return
def __eq__(self, other):
try:
return self.priority == other.priority
except AttributeError:
return NotImplemented
def __lt__(self, other):
try:
return self.priority < other.priority
except AttributeError:
return NotImplemented
q = queue.PriorityQueue()
q.put(Job(3, "Mid-level job"))
q.put(Job(10, "Low-level job"))
q.put(Job(1, "Important job"))
def process_job(q):
while True:
# 根據優先級別來拿到新的工作,越重要的越先拿到
next_job = q.get()
print("processing job:", next_job.description, threading.current_thread().getName())
q.task_done()
workers = [
threading.Thread(name="Thread888", target=process_job, args=(q,))
]
for w in workers:
w.setDaemon(True)
w.start()
q.join()
顯示結果:
New job: Mid-level job New job: Low-level job New job: Important job processing job: Important job Thread888 processing job: Mid-level job Thread888 processing job: Low-level job Thread888
