找回密碼
 註冊
搜索
查看: 467|回復: 0

[教學] python 用 threading array loop 執行緒 跑 陣列迴圈

[複製鏈接]
發表於 3 天前 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
要使用 Python 的threadingThread 模組並發處理數組(或列表)中的元素,可以建立和管理多個線程,每個線程負責處理數組的一部分或特定元素。 這種方法對於 I/O 密集型任務尤其有利,因為執行緒會花費大量時間等待外部資源(例如網路請求或檔案操作),而其他執行緒可以在這些等待期間執行。
以下是一個使用線程處理數組的基本範例:


  1. import threading
  2. import time

  3. def process_element(element, result_list, index):
  4.     """A function to simulate processing an element."""
  5.     print(f"Processing element {element} in thread {threading.current_thread().name}")
  6.     time.sleep(0.1)  # Simulate some work or I/O operation
  7.     processed_value = element * 2
  8.     result_list[index] = processed_value
  9.     print(f"Finished processing element {element}, result: {processed_value}")

  10. def threaded_array_processing(data_array):
  11.     """Processes an array using multiple threads."""
  12.     results = [None] * len(data_array)  # Initialize a list to store results
  13.     threads = []

  14.     for i, element in enumerate(data_array):
  15.         # Create a thread for each element (or chunk of elements)
  16.         thread = threading.Thread(target=process_element, args=(element, results, i), name=f"Thread-{i}")
  17.         threads.append(thread)
  18.         thread.start()

  19.     # Wait for all threads to complete
  20.     for thread in threads:
  21.         thread.join()

  22.     return results

  23. if __name__ == "__main__":
  24.     my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  25.     print(f"Original array: {my_array}")

  26.     processed_array = threaded_array_processing(my_array)
  27.     print(f"Processed array: {processed_array}")
複製代碼


解釋:
process_element(element, result_list, index)功能: 此函數表示每個執行緒將執行的任務。 它接受一個元素、一個result_list用於儲存處理後輸出的共享對象,以及一個index用於正確放置結果的參數。
threaded_array_processing(data_array)功能:
它初始化results一個與 大小相同的列表data_array,用於保存已處理的值。
它遍歷,為每個元素data_array創建一個新的。threading.Thread
target指定要由執行緒執行的函數(process_element)。
args提供要傳遞給函數的參數target。
thread.start()啟動線程的執行。
thread.join()確保主程式等待每個執行緒完成後再繼續執行,從而確保收集所有結果。
if __name__ == "__main__":堵塞:

這示範如何threaded_array_processing使用範例陣列呼叫函數,並列印原始結果和處理後的結果。
注意事項:
全域解釋器鎖定(GIL): 在 CPython 中,GIL 限制了單一進程內多個執行緒之間真正並行執行 Python 字節碼的能力。 雖然執行緒適用於 I/O 密集型任務,但對於 CPU 密集型任務,multiprocessing使用獨立進程(每個進程都有自己的 Python 解釋器和 GIL)的模組通常更有效。
螺紋安全: 當多個執行緒存取和修改共享資料時(如result_list範例所示),可能需要同步機制(例如同步threading.Lock或同步)來防止競爭條件並確保資料完整性,尤其是對於更複雜的操作。threading.Semaphore
concurrent.futures模組: 為了以更高層級且通常更方便的方式管理執行緒池和處理結果,請考慮使用concurrent.futures.ThreadPoolExecutor。




 
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-11-9 06:51 , Processed in 0.021816 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表