多线程是提高程序性能的重要手段,尤其在处理I/O密集型任务时表现突出。以下是关键知识点梳理:

📌 核心概念

  • 线程:程序执行的最小单元,共享进程资源但拥有独立的执行路径
  • GIL(全局解释器锁):Python的线程调度机制,限制同一时间仅一个线程执行
  • 并发 vs 并行:并发指多个任务交替执行,并行指同时执行(需多核CPU)

🧠 线程 vs 进程

特性 线程 进程
资源开销 小(共享内存空间) 大(独立内存空间)
上下文切换 快速 较慢
通信效率 高(同一进程内) 低(需IPC机制)
适用场景 I/O密集型任务 计算密集型任务

📚 Python 多线程实践

  1. 使用 threading 模块创建线程

    import threading
    
    def worker():
        print("线程运行中")
    
    t = threading.Thread(target=worker)
    t.start()
    
  2. 线程同步工具:

    • threading.Lock:互斥锁
    • threading.Condition:条件变量
    • threading.Semaphore:信号量
  3. 线程池管理:

    from concurrent.futures import ThreadPoolExecutor
    
    with ThreadPoolExecutor(max_workers=5) as executor:
        executor.submit(task1)
        executor.submit(task2)
    

📈 典型应用场景

  • 网络请求处理(如爬虫)
  • 数据库操作
  • GUI界面响应
  • 文件读写操作

📖 推荐学习路径

Python threading Module

注意:Python的多线程适合I/O密集型任务,计算密集型建议使用多进程或C扩展。如需深入理解GIL机制,可参考Python执行模型详解