Python并发编程:多线程与多进程实战指南
在Python中处理大量任务时,并发编程能够显著提升程序性能。本文将详细介绍Python中的多线程和多进程技术,帮助你掌握并发编程的核心知识。
一、并发编程基础
1. 什么是并发?
并发是指程序同时处理多个任务的能力。在单核CPU上,这是通过时间片轮转实现的,让不同任务快速切换执行。
2. 多线程 vs 多进程
- 多线程:共享内存空间,上下文切换快,但存在全局解释器锁(GIL)限制
-
- 多进程:独立内存空间,不受GIL限制,但上下文切换开销大
-
二、多线程实现
-
1. 创建线程
-
- import threading
- def worker():
-
print('Thread is working...') -
# 创建线程 -
thread = threading.Thread(target=worker) -
thread.start() -
thread.join() -
``` -
### 2. 线程同步 -
```python -
from threading import Lock, Semaphore -
lock = Lock() -
semaphore = Semaphore(3) # 限制同时访问数量 -
``` -
### 3. 线程安全 -
```python -
# 使用 Lock -
with lock: -
# 线程安全代码 -
# 使用 Semaphore -
semaphore.acquire() -
# 使用后释放 -
semaphore.release() -
``` -
## 三、多进程实现 -
### 1. 创建进程 -
```python -
from multiprocessing import Process -
def worker_process(): -
print('Process is working...') -
# 创建进程 -
process = Process(target=worker_process) -
process.start() -
process.join() -
``` -
### 2. 进程间通信 -
```python -
from multiprocessing import Pipe, Queue -
# 使用 Pipe -
parent_conn, child_conn = Pipe() -
parent_conn.send('hello') -
msg = child_conn.recv() -
# 使用 Queue -
queue = Queue() -
queue.put('data') -
data = queue.get() -
``` -
### 3. 批量进程 -
```python -
from multiprocessing import Pool -
def square(n): -
return n * n -
if __name__ == '__main__': -
with Pool(4) as p: -
results = p.map(square, range(10)) -
print(results) -
``` -
## 四、实战案例 -
### 1. 并发爬虫 -
```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'] -
with ThreadPoolExecutor(max_workers=5) as executor: -
results = list(executor.map(fetch_url, urls)) -
print(results) -
``` -
### 2. 并发计算 -
```python -
from multiprocessing import Pool -
import time -
def compute(n): -
time.sleep(1) -
return n * n -
if __name__ == '__main__': -
with Pool(4) as p: -
results = p.map(compute, range(10)) -
print(results) -
``` -
## 五、性能优化建议 -
1. **避免在I/O密集型任务中使用GIL**:使用多线程处理网络请求 -
2. **计算密集型任务使用多进程**:充分利用多核CPU -
3. **合理设置线程/进程数量**:根据CPU核心数调整 -
4. **使用异步IO**:对于IO密集型任务,考虑asyncio -
## 六、总结 -
并发编程能够显著提升Python程序的性能,但需要根据实际场景选择合适的技术: -
- **I/O密集型任务**:优先考虑多线程 -
- **计算密集型任务**:优先考虑多进程 -
- **复杂场景**:考虑异步IO或混合方案 -
掌握这些技术,让你的Python程序更高效!