如何在 Python 中實現優先順序佇列?
簡介...
queue 模組提供了一個先進先出 (FIFO) 和後進先出 (LIFO) 的資料結構,適用於多執行緒程式設計。佇列可以安全地用於在建立者和使用者執行緒之間傳遞資料或任何廣泛的資訊,例如會話詳細資訊、路徑、變數等。鎖定通常由呼叫者處理。
注意:本討論假設您已經瞭解佇列的一般性質。如果您不瞭解,您可能需要閱讀一些參考內容後再繼續。
1. 讓我們實現一個基本的 FIFO 佇列。
import queue
fifo = queue.Queue()
# put numbers into queue
for i in range(5):
fifo.put(i)
# if not empty get the numbers from queue
print(f"Ouput \n")
while not fifo.empty():
print(f" {fifo.get()} ")輸出
0 1 2 3 4
2. 上述示例使用單個執行緒來展示元素如何按照插入順序從佇列中移除。
3. 讓我們實現一個基本的 LIFO 佇列。
import queue
lifo = queue.LifoQueue()
# put numbers into queue
for i in range(5):
lifo.put(i)
print(f"Ouput \n")
# if not empty get the numbers from queue
while not lifo.empty():
print(f" {lifo.get()} ")輸出
4 3 2 1 0
4. 上述示例顯示,最近放入佇列的元素會被 get() 方法移除。
5. 最後,我們將瞭解如何實現優先順序佇列。
有時,佇列中專案的處理順序需要基於這些專案的優先順序,而不是它們建立或新增到佇列的順序。例如,生產環境中執行的關鍵業務作業需要最高的 CPU 和優先順序,優先於開發人員想要列印的列印作業。PriorityQueue 使用佇列內容的排序順序來決定要檢索哪個專案。
import queue
import threading
# Class to get the priority and description and validate the priority
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
# create a priority queue and define the priority
q = queue.PriorityQueue()
q.put(Job(90, 'Developer-Print job'))
q.put(Job(2, 'Business-Report job'))
q.put(Job(1, 'Business-Critical Job'))
# process the job
def process_job(q):
while True:
next_job = q.get()
print(f" *** Now, Processing the job - {next_job.description}")
q.task_done()
# define the threads
workers = [
threading.Thread(target=process_job, args=(q,)),
threading.Thread(target=process_job, args=(q,)), ]
# call the threads and join them.
for w in workers:
w.setDaemon(True)
w.start()
q.join()輸出
job: Developer-Print job New job: Business-Report job New job: Business-Critical Job
輸出
*** Now, Processing the job - Business-Critical Job *** Now, Processing the job - Business-Report job *** Now, Processing the job - Developer-Print job
6. 此示例有多個執行緒消費作業,這些作業根據呼叫 get() 時佇列中專案的優先順序進行處理。處理順序基於業務關鍵性,而不管它們新增的順序如何。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP