如何使用 Python 實現多執行緒佇列
簡介..
在這個例子中,我們將建立一個任務佇列,它儲存所有要執行的任務,以及一個與佇列互動以單獨處理其元素的執行緒池。
我們將從問題開始,什麼是佇列?佇列是一種資料結構,它是一組以非常特定的順序維護的不同元素的集合。讓我舉一個現實生活中的例子來解釋。
假設你在雜貨店櫃檯排隊支付雜貨賬單(別問我哪家雜貨店)
在排隊等候支付賬單的人群中,你會注意到以下幾點
1. 人們從佇列的一端進入,從另一端離開。
2. 如果 A 先生在 B 先生之前進入佇列,則 A 先生會在 B 先生之前離開佇列(除非 B 先生是名人或有更高的優先順序)。
3. 一旦每個人都支付了賬單,佇列中將不再有人。
好了,回到程式設計中,佇列的工作方式與此類似。
1. 入隊 - 元素新增到佇列的末尾。
2. 出隊 - 從佇列的開頭刪除元素。
還有更多,先進先出 (FIFO) - 最先新增的元素將最先被刪除。後進先出 (LIFO) - 最後新增的元素將最先被刪除。
Python 如何實現佇列資料結構?
Python 中的 queue 模組提供了佇列資料結構的簡單實現。每個佇列可以具有以下方法。
get(): 返回下一個元素。
put(): 新增一個新元素。
qsize(): 佇列中當前元素的數量。
empty(): 返回一個布林值,指示佇列是否為空。
full(): 返回一個布林值,指示佇列是否已滿。
1. 我們將建立一個函式,它接受一個引數 x,然後迭代 1 到自身 (x) 之間的數字,以執行乘法。例如,當你將 5 傳遞給此函式時,它會迭代 1 到 5 並繼續進行乘法,即 1 乘以 5,2 乘以 5,3 乘以 5,4 乘以 5,5 乘以 5,最終將值作為列表返回。
示例
def print_multiply(x):
output_value = []
for i in range(1, x + 1):
output_value.append(i * x)
print(f"Output \n *** The multiplication result for the {x} is - {output_value}")
print_multiply(5)輸出
*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]
2. 我們將編寫另一個名為 process_queue() 的函式,該函式將嘗試獲取佇列物件的下一個元素。此邏輯非常簡單,繼續傳遞元素,直到佇列為空。我將使用 sleep 來稍微延遲處理。
示例
def process_queue(): while True: try: value = my_queue.get(block=False) except queue.Empty: return else: print_multiply(value) time.sleep(2)
3. 建立一個類,當初始化並啟動新例項時,將呼叫 process_queue() 函式。
示例
class MultiThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
print(f" ** Starting the thread - {self.name}")
process_queue()
print(f" ** Completed the thread - {self.name}")4. 最後,我們將傳遞輸入數字列表並填充佇列。
# setting up variables input_values = [5, 10, 15, 20] # fill the queue my_queue = queue.Queue() for x in input_values: my_queue.put(x)
5. 最後,將所有內容放在一起。
import queue
import threading
import time
# Class
class MultiThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
print(f"Output \n ** Starting the thread - {self.name}")
process_queue()
print(f" ** Completed the thread - {self.name}")
# Process thr queue
def process_queue():
while True:
try:
value = my_queue.get(block=False)
except queue.Empty:
return
else:
print_multiply(value)
time.sleep(2)
# function to multiply
def print_multiply(x):
output_value = []
for i in range(1, x + 1):
output_value.append(i * x)
print(f" \n *** The multiplication result for the {x} is - {output_value}")
# Input variables
input_values = [2, 4, 6, 5,10,3]
# fill the queue
my_queue = queue.Queue()
for x in input_values:
my_queue.put(x)
# initializing and starting 3 threads
thread1 = MultiThread('First')
thread2 = MultiThread('Second')
thread3 = MultiThread('Third')
thread4 = MultiThread('Fourth')
# Start the threads
thread1.start()
thread2.start()
thread3.start()
thread4.start()
# Join the threads
thread1.join()
thread2.join()
thread3.join()
thread4.join()輸出
** Starting the thread - First *** The multiplication result for the 2 is - [2, 4]
輸出
** Starting the thread - Second *** The multiplication result for the 4 is - [4, 8, 12, 16]
輸出
** Starting the thread - Third *** The multiplication result for the 6 is - [6, 12, 18, 24, 30, 36]
輸出
** Starting the thread - Fourth *** The multiplication result for the 5 is - [5, 10, 15, 20, 25] *** The multiplication result for the 10 is - [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] *** The multiplication result for the 3 is - [3, 6, 9] ** Completed the thread - Third ** Completed the thread - Fourth ** Completed the thread - Second ** Completed the thread - First
6. 我們已成功實現了佇列概念。看,我們有 4 個執行緒,但有 6 個值要處理,所以誰先到達佇列就會被執行,其他執行緒將排隊等待其他人完成。
這類似於現實生活,假設有 3 個櫃檯,但有 10 個人在等候支付賬單,因此 10 個人將在 3 個佇列中,誰先支付完賬單就會離開佇列,為下一個人騰出位置。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP