>探索我的亞馬遜作者頁面以獲取各種各樣的書籍。 在Medium上關注我以獲取更多見解和更新!非常感謝您的支持。
>解鎖Python的多執行緒和多處理功能的功能,以顯著提高應用程式的速度和效率。本指南揭示了有效利用這些功能的八種基本技術。
> 透過I/O結合操作螺紋出色。 Python'sthreading
模組提供了用於執行緒管理的使用者友善介面。 這是同時下載多個檔案的方法:
import threading import requests def download_file(url): response = requests.get(url) filename = url.split('/')[-1] with open(filename, 'wb') as f: f.write(response.content) print(f"Downloaded {filename}") urls = ['http://example.com/file1.txt', 'http://example.com/file2.txt', 'http://example.com/file3.txt'] threads = [] for url in urls: thread = threading.Thread(target=download_file, args=(url,)) threads.append(thread) thread.start() for thread in threads: thread.join() print("All downloads complete")
此程式碼將每個下載分配給單獨的線程,啟用同時執行。
對於結合CPU的任務,由於Python的全局解釋器鎖(GIL),此模組是優越的。 多處理創建獨立的過程,每個過程都有自己的記憶體空間和GIL,避免了GIL的限制。 這是一個並行計算的範例:
multiprocessing
import multiprocessing def calculate_square(number): return number * number if __name__ == '__main__': numbers = range(10) with multiprocessing.Pool() as pool: results = pool.map(calculate_square, numbers) print(results)
>的範例:concurrent.futures
ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor import time def worker(n): print(f"Worker {n} starting") time.sleep(2) print(f"Worker {n} finished") with ThreadPoolExecutor(max_workers=3) as executor: executor.map(worker, range(5)) print("All workers complete")
對於非同步I/O,
模組發光,可以透過coroutines啟用有效的非同步程式設計。這是一個範例:
asyncio
import asyncio import aiohttp async def fetch_url(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def main(): urls = ['http://example.com', 'http://example.org', 'http://example.net'] tasks = [fetch_url(url) for url in urls] results = await asyncio.gather(*tasks) for url, result in zip(urls, results): print(f"Content length of {url}: {len(result)}") asyncio.run(main())
這顯示了跨多個過程的安全計數器增量。
>
當多個執行緒存取共享資源時,執行緒同步可以防止種族條件。 Python提供的同步原始素,例如multiprocessing
:Value
from multiprocessing import Process, Value import time def increment(counter): for _ in range(100): with counter.get_lock(): counter.value += 1 time.sleep(0.01) if __name__ == '__main__': counter = Value('i', 0) processes = [Process(target=increment, args=(counter,)) for _ in range(4)] for p in processes: p.start() for p in processes: p.join() print(f"Final counter value: {counter.value}")
Lock
import threading class Counter: def __init__(self): self.count = 0 self.lock = threading.Lock() def increment(self): with self.lock: self.count += 1 def worker(counter, num_increments): for _ in range(num_increments): counter.increment() counter = Counter() threads = [] for _ in range(5): thread = threading.Thread(target=worker, args=(counter, 100000)) threads.append(thread) thread.start() for thread in threads: thread.join() print(f"Final count: {counter.count}")
在多執行緒和多處理之間進行選擇取決於任務。 I/O 密集型任務受益於多線程,而 CPU 密集型任務通常需要多處理才能實現真正的並行性。 負載平衡和任務依賴性是平行處理的關鍵考慮因素。 處理共享資源時,適當的同步機制至關重要。 效能比較因任務和系統而異。 在數據處理和科學計算中,多重處理非常有效。 對於 Web 應用程序,asyncio
提供了並發連接的高效處理。 Python 多樣化的平行處理工具使開發人員能夠創建高效能應用程式。
101本書
101 Books 是一家由人工智慧驅動的出版社,由作家Aarav Joshi 共同創立,提供價格實惠、高品質的書籍— 有些價格低至 4 美元.
在亞馬遜上探索我們的Golang Clean Code書籍。 搜尋 Aarav Joshi 尋找更多書籍和特別折扣!
我們的其他項目
探索我們的其他項目:投資者中心(英語、西班牙語、德語)、智能生活、時代與迴響、令人費解的奧秘、印度教、菁英Dev 和JS 學校。
在 Medium 上追蹤我們
透過 Medium 與我們聯絡:Tech Koala Insights、Epochs & Echoes World、Investor Central Medium、Puzzling Mystersteries Medium、🎜> 科學與時代媒介,以及現代印度教。
以上是用於多線程和多處理的python技術:提高您的應用程序性能的詳細內容。更多資訊請關注PHP中文網其他相關文章!