生活场景类比
假设某银行有:
- 1个营业厅(进程):独立建筑,有独立金库
- 3个柜台窗口(线程):共享营业厅资源
场景一:单线程模式(普通营业厅)
# 传统单线程:只有一个窗口服务所有客户
def handle_customer(customer):
print(f"👨💼 {customer} 开始办理业务")
time.sleep(3) # 模拟耗时操作(如填写表格)
print(f"✅ {customer} 办理完成")
customers = ["客户A", "客户B", "客户C"]
for c in customers:
handle_customer(c)
输出(总耗时约9秒):
👨💼 客户A 开始办理业务
✅ 客户A 办理完成
👨💼 客户B 开始办理业务
✅ 客户B 办理完成
👨💼 客户C 开始办理业务
✅ 客户C 办理完成
场景二:多线程模式(多个窗口)
import threading
import time
# 线程函数:处理单个客户业务
def handle_customer(customer):
print(f"👨💼 {customer} 在{threading.current_thread().name}开始办理")
time.sleep(3)
print(f"✅ {customer} 在{threading.current_thread().name}办理完成")
customers = ["客户A", "客户B", "客户C"]
threads = []
# 创建并启动3个线程(开3个窗口)
for c in customers:
# 关键参数说明:
# target: 线程要执行的函数
# args: 传递给函数的参数(必须是元组)
t = threading.Thread(target=handle_customer, args=(c,))
threads.append(t)
t.start() # 启动线程
# 等待所有线程完成
for t in threads:
t.join() # 让主线程等待子线程结束
print("所有客户业务办理完毕")
输出(总耗时约3秒):
👨💼 客户A 在Thread-1开始办理
👨💼 客户B 在Thread-2开始办理
👨💼 客户C 在Thread-3开始办理
✅ 客户A 在Thread-1办理完成
✅ 客户B 在Thread-2办理完成
✅ 客户C 在Thread-3办理完成
所有客户业务办理完毕
场景三:多进程模式(多个营业厅)
import multiprocessing
import time
# 进程函数:处理客户群体业务
def handle_customers(hall_id):
print(f"🏦 营业厅{hall_id}开始工作")
time.sleep(3) # 模拟处理业务
print(f"🏁 营业厅{hall_id}业务完成")
# 创建3个进程(开3个营业厅)
processes = []
for i in range(3):
# 关键参数说明:
# target: 进程要执行的函数
# args: 传递给函数的参数(必须是元组)
p = multiprocessing.Process(target=handle_customers, args=(i+1,))
processes.append(p)
p.start() # 启动进程
# 等待所有进程结束
for p in processes:
p.join() # 让主进程等待子进程结束
print("所有营业厅关闭")
输出(总耗时约3秒):
🏦 营业厅1开始工作
🏦 营业厅2开始工作
🏦 营业厅3开始工作
🏁 营业厅1业务完成
🏁 营业厅2业务完成
🏁 营业厅3业务完成
所有营业厅关闭
如何选择?黄金决策法则
1 需要频繁数据交换 → 优先考虑多线程
示例:网页爬虫(多个爬虫共享结果队列)
2.计算密集型任务 → 必须使用多进程
示例:视频转码/大数据分析
.3. 既要性能又要安全 → 混合使用
示例:用多进程处理核心计算,每个进程内用多线程处理I/O
💡 理解技巧:
- 把进程想象成独立公司,线程是公司里的各部门
- 多线程就像公司各部门共享打印机(需排队),多进程就像每个公司有自己的打印机
- Python的GIL锁相当于公司规定:同一时刻只能有一个部门使用打印机(所以多线程不适合计算密集型任务)