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()時佇列中元素的優先級來處理,運行消費者執行緒時,增加到佇列的元素的處理順序取決于執行緒背景關系切換,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/189227.html
標籤:Python
上一篇:web自動化之三大等待
下一篇:Python 爬取必應壁紙
