Yoru Karu Studio

程式設計學習筆記 | 生活心得

05-1. Python GIL 深度解析 ⏱️ 閱讀時間: 15 分鐘 🎯 難度: ⭐⭐⭐ (中等) 🎯 本篇重點 深入理解 Python GIL (Global Interpreter Lock) 的原理、影響以及如何繞過它。 🤔 什麼是 GIL? GIL (Global Interpreter Lock) = 全域解釋器鎖 一句話解釋: GIL 是 Python 解釋器(CPython)的一把全域鎖,確保同一時間只有一個 Thread 可以執行 Python 程式碼。 🏢 用廚房來比喻 沒有 GIL 的語言(如 Java、C++) 廚房(CPU) ├─ 爐子 1(核心 1)→ 廚師 A 炒菜 ├─ 爐子 2(核心 2)→ 廚師 B 炒菜 ├─ 爐子 3(核心 3)→ 廚師 C 炒菜 └─ 爐子 4(核心 4)→ 廚師 D 炒菜 4 個廚師可以同時使用 4 個爐子 ← 真正並行有 GIL 的 Python 廚房(CPU) ├─ 爐子 1(核心 1) ├─ 爐子 2(核心 2) ├─ 爐子 3(核心 3) └─ 爐子 4(核心 4) 但只有一把廚房鑰匙(GIL)! ├─ 廚師 A 持有鑰匙 → 可以用爐子 1 ├─ 廚師 B 等待鑰匙 → 無法工作 ├─ 廚師 C 等待鑰匙 → 無法工作 └─ 廚師 D 等待鑰匙 → 無法工作 同一時間只有一個廚師可以工作 ← 無法並行 🔍 GIL 的實際影響 案例 1:CPU 密集型任務 import time from threading import Thread def cpu_task(): """CPU 密集計算""" total = 0 for i in range(10000000): total += i * i return total # 單 Thread start = time.

05-2. threading 模組完整指南 ⏱️ 閱讀時間: 15 分鐘 🎯 難度: ⭐⭐ (簡單) 🎯 本篇重點 完整掌握 Python threading 模組,包含 Thread 創建、同步機制、Thread Pool、最佳實踐等核心功能。 📚 threading 模組概覽 threading 是 Python 標準庫中用於創建和管理多執行緒的模組,適合 I/O 密集型任務。 from threading import Thread, Lock, Semaphore, Event, Condition from threading import current_thread, enumerate, active_count 1️⃣ 創建 Thread 方法 1:函式作為 target from threading import Thread import time def worker(name, sleep_time): """Worker 函式""" print(f"[{name}] 開始工作...") time.sleep(sleep_time) print(f"[{name}] 完成工作") # 創建 Thread t1 = Thread(target=worker, args=('Worker-1', 2)) t2 = Thread(target=worker, args=('Worker-2', 3)) # 啟動 t1.

05-3. multiprocessing 模組完整指南 ⏱️ 閱讀時間: 20 分鐘 🎯 難度: ⭐⭐⭐ (中等) 🎯 本篇重點 完整掌握 Python multiprocessing 模組,包含 Process 創建、Pool 管理、資料共享、進程間通訊(IPC)等所有核心功能。 📚 multiprocessing 概覽 multiprocessing 是 Python 標準庫中用於創建和管理多個 Process 的模組,可以繞過 GIL 限制,實現真正的並行計算。 from multiprocessing import Process, Pool, Queue, Pipe, Manager from multiprocessing import Value, Array, Lock 1️⃣ 基礎:創建 Process 方法 1:函式作為 target from multiprocessing import Process import os import time def worker(name, sleep_time): """Worker 函式""" print(f"[{name}] PID: {os.getpid()}, 父 PID: {os.getppid()}") print(f"[{name}] 開始工作.

05-4. concurrent.futures 使用指南 ⏱️ 閱讀時間: 12 分鐘 🎯 難度: ⭐⭐ (簡單) 🎯 本篇重點 掌握 Python concurrent.futures 模組,這是一個高層級的併發介面,統一了 Thread 和 Process 的使用方式。 🤔 為什麼需要 concurrent.futures? 傳統方式的問題 # threading:手動管理 Thread from threading import Thread threads = [] for task in tasks: t = Thread(target=work, args=(task,)) t.start() threads.append(t) for t in threads: t.join() # multiprocessing:手動管理 Process from multiprocessing import Process processes = [] for task in tasks: p = Process(target=work, args=(task,)) p.start() processes.append(p) for p in processes: p.

05-5. asyncio 基礎概念 ⏱️ 閱讀時間: 15 分鐘 🎯 難度: ⭐⭐⭐ (中等) 🎯 本篇重點 理解 asyncio 的核心概念,包含協程(Coroutine)、事件循環(Event Loop)、非同步 I/O,以及如何使用 async/await 語法。 🤔 什麼是 asyncio? asyncio = Asynchronous I/O(非同步輸入輸出) 一句話解釋: asyncio 是 Python 的非同步程式設計框架,使用單 Thread 處理大量 I/O 操作,無需多執行緒或多進程。 🏢 餐廳比喻 傳統同步(Synchronous) 一個服務生(Thread) ├─ 接待客人 A → 點餐 → 等廚房做菜(阻塞)→ 送餐 └─ 接待客人 B → ...(要等客人 A 完成) 問題:服務生在等廚房時閒置,效率低多執行緒(Multi-threading) 三個服務生(3 個 Thread) ├─ 服務生 1 → 客人 A(等廚房時阻塞) ├─ 服務生 2 → 客人 B(等廚房時阻塞) └─ 服務生 3 → 客人 C(等廚房時阻塞) 優點:可同時服務多位客人 缺點:服務生多了成本高(記憶體)asyncio(非同步) 一個服務生(1 個 Thread) ├─ 客人 A 點餐 → 交給廚房 → 不等待,去服務客人 B ├─ 客人 B 點餐 → 交給廚房 → 不等待,去服務客人 C ├─ 客人 C 點餐 → 交給廚房 → 回去檢查客人 A 的餐好了沒 └─ 客人 A 的餐好了 → 送餐 → 繼續服務其他客人 優點:一個服務生高效服務多位客人 關鍵:不等待,持續切換任務 💻 asyncio vs Thread vs Process 特性 asyncio Thread Process 並發模型 協程(單 Thread) 多 Thread 多 Process 適用場景 I/O 密集型 I/O 密集型 CPU 密集型 記憶體佔用 極低(KB) 低(MB) 高(MB) 創建速度 極快 快 慢 最大數量 數萬+ 數百 數十 GIL 影響 無(單 Thread) 有 無 切換成本 極低(無上下文切換) 中 高 1️⃣ 基礎:async 和 await 同步 vs 非同步 import time # 同步版本 def fetch_data(): print("開始獲取資料.

📚 作業系統與併發處理系列 - 目錄 01. Process 基礎篇 01-1. Process 是什麼 ⏱️ 8min 01-2. Process 的組成(Code, Data, Stack, Heap) ⏱️ 10min 01-3. Process 的生命週期 ⏱️ 10min 01-4. Context Switch 詳解 ⏱️ 12min 01-5. Process vs Thread 完整對比 ⏱️ 10min 02. Thread 基礎篇 02-1. Thread 是什麼 ⏱️ 8min 02-2. Thread 的優缺點 ⏱️ 10min 02-3. Multi-threading vs Multi-processing ⏱️ 12min 02-4. 何時用 Thread?何時用 Process? ⏱️ 10min 03. Inter-Process Communication (IPC) 篇 03-1. IPC 概述 ⏱️ 8min 03-2.
0%