Python并发编程:多线程与多进程的实战指南

Python并发编程:多线程与多进程的实战指南

在Python中处理大量任务时,并发编程能够显著提升程序性能。本文将详细介绍多线程与多进程的实现方法及适用场景。

什么是并发?

并发是指程序同时处理多个任务的能力。在Python中,有两种主要的并发方式:

多线程

多线程是在同一个进程内创建多个执行线程,共享进程的内存空间。适用于I/O密集型任务。

python 复制代码
import threading
import time

def print_numbers():
    for i in range(5):
        time.sleep(1)
        print(f'Thread {threading.current_thread().name}: {i}')

t1 = threading.Thread(target=print_numbers, name='Thread-1')
t2 = threading.Thread(target=print_numbers, name='Thread-2')
t1.start()
t2.start()
t1.join()
t2.join()

多进程

多进程是通过创建多个独立的进程来并行执行任务,每个进程有独立的内存空间。适用于CPU密集型任务。

python 复制代码
from multiprocessing import Process
import time

def calculate():
    print('Starting calculation...')
    time.sleep(3)
    print('Calculation complete')

p1 = Process(target=calculate)
p2 = Process(target=calculate)
p1.start()
p2.start()
p1.join()
p2.join()

多线程 vs 多进程

特性 多线程 多进程
内存共享
启动开销
上下文切换
适用场景 I/O密集型 CPU密集型

实战案例:爬虫并发

python 复制代码
import requests
from concurrent.futures import ThreadPoolExecutor

def fetch_url(url):
    response = requests.get(url)
    return response.text

urls = ['https://example.com', 'https://juejin.cn', 'https://zhihu.com']

with ThreadPoolExecutor(max_workers=5) as executor:
    results = list(executor.map(fetch_url, urls))
    print(results)

最佳实践

  1. 避免全局解释器锁(GIL):多线程在Python中受GIL限制,不适合CPU密集型任务
  2. 使用合适的数据结构:线程间共享数据时注意同步
  3. 合理设置线程池大小:根据CPU核心数调整
  4. 监控资源使用:避免过度消耗系统资源

总结

  • 多线程适合I/O密集型任务
  • 多进程适合CPU密集型任务
  • 根据实际需求选择合适的并发方式
  • 注意资源管理和性能优化
相关推荐
livemetee20 小时前
【关于Spring声明式事务】
java·后端·spring
techdashen1 天前
Arborium:把 tree-sitter 语法高亮打包成 Rust 文档生态的基础设施
开发语言·后端·rust
Profile排查笔记1 天前
指纹浏览器环境异常排查:Fingerprint、Profile、Proxy、Session 和 Task Log 怎么看
前端·人工智能·后端·自动化
小强库计算机毕业设计1 天前
源码分享Spring Boot + Vue3 的校园社团管理系统
java·spring boot·后端·计算机毕业设计
阿新聊ai1 天前
从 Prompt 到 Loop:AI 编程 Agent 四代循环的演进全景
人工智能·后端
im_lanny1 天前
从 Function Calling 到 MCP:Agent 工具调用的三层境界与生产级安全护栏
后端
agent8971 天前
Spring Boot 接口超时治理:从连接池、线程池到熔断限流的完整排查思路
java·spring boot·后端
雨师@1 天前
go语言项目--实例化(图书管理)--005
开发语言·后端·golang
Aspiresky1 天前
探索Rust语言之引用
开发语言·后端·rust
geovindu1 天前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式