1. queue線程安全的FIFO實現
queue模塊提供了一個適用於多線程編程的先進先出(FIFO,first-in,first-out)數據結構,可以用來在生產者和消費者線程之間安全地傳遞消息或其他數據。它會為調用者處理鎖定,使多個線程可以安全而容易地處理同一個Queue實例。Queue的大小(其中包含的元素個數)可能受限,以限制內存使用或處理。
1.1 基本FIFO隊列
Queue類實現了一個基本的先進先出容器。使用put()將元素增加到這個序列的一端,使用get()從另一端刪除。
import queue q = queue.Queue() for i in range(5): q.put(i) while not q.empty(): print(q.get(), end=' ') print()
這個例子使用了一個線程來展示按插入元素的相同順序從隊列刪除元素。
1.2 LIFO隊列
與Queue的標准FIFO實現相反,LifoQueue使用了(通常與棧數據結構關聯的)后進后出(LIFO,last-in,first-out)順序。
import queue q = queue.LifoQueue() for i in range(5): q.put(i) while not q.empty(): print(q.get(), end=' ') print()
get將刪除最近使用put插入到隊列的元素。
1.3 優先隊列
有些情況下,需要根據隊列中元素的特性來決定這些元素的處理順序,而不是簡單地采用在隊列中創建或插入元素的順序。例如,工資部門的打印作業可能就優先於某個開發人員想要打印的代碼清單。PriorityQueue使用隊列內容的有序順序來決定獲取哪一個元素。
import functools import queue 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) q.task_done() workers = [ threading.Thread(target=process_job, args=(q,)), threading.Thread(target=process_job, args=(q,)), ] for w in workers: w.setDaemon(True) w.start() q.join()
這個例子有多個線程在處理作業,要根據調用get()時隊列中元素的優先級來處理。運行消費者線程時,增加到隊列的元素的處理順序取決於線程上下文切換。