🌐 什么是多线程?

多线程是 Python 中实现并发的一种方式,通过同时运行多个线程(轻量级进程)来提高程序效率。
💡 注意:Python 的全局解释器锁(GIL)限制了多线程在 CPU密集型任务中的性能提升,但适用于 I/O 密集型场景。

📌 核心概念

  • 线程:独立执行路径,共享主进程内存空间
  • GIL:确保同一时间只有一个线程执行 Python 字节码
  • 并发 vs 并行:并发指多个任务交替执行,而并行指真正同时执行

🧩 如何创建线程?

方法一:threading 模块

import threading

def worker():
    print("线程正在运行")

thread = threading.Thread(target=worker)
thread.start()
thread.join()

👉 深入理解 threading 模块

方法二:继承 Thread

class MyThread(threading.Thread):
    def run(self):
        print("继承线程类执行中")

t = MyThread()
t.start()

🔒 线程同步机制

1. 锁(Lock)

lock = threading.Lock()
with lock:
    # 安全操作共享资源

2. 信号量(Semaphore)

semaphore = threading.Semaphore(2)
semaphore.acquire()
# 执行代码
semaphore.release()

3. 条件变量(Condition)

condition = threading.Condition()
with condition:
    condition.wait()  # 等待条件满足
    condition.notify()  # 通知其他线程

🧠 线程池(ThreadPoolExecutor)

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=3) as executor:
    executor.map(task, [1, 2, 3])

👉 线程池实战案例

⚠️ 注意事项

  • 避免共享可变状态(使用 threading.local() 或队列)
  • 使用 join() 确保主线程等待子线程完成
  • 慎用多线程:CPU 密集型任务推荐使用多进程(multiprocessing

📚 扩展阅读

python_multithreading