# 9. Python 并发与并行编程
## 多线程编程
### 概述
多线程编程是一种并发编程的方式,允许程序在同一时间内执行多个线程。每个线程可以独立运行,共享相同的内存空间。Python 提供了 `threading` 模块来支持多线程编程。
### 线程的创建与启动
在 Python 中,可以通过继承 `threading.Thread` 类或直接使用 `threading.Thread` 对象来创建线程。以下是一个简单的示例:
```python
import threading
def worker():
print("Worker thread is running")
# 创建线程
thread = threading.Thread(target=worker)
# 启动线程
thread.start()
# 等待线程完成
thread.join()
线程同步
由于多个线程共享相同的内存空间,可能会导致数据竞争问题。为了避免这种情况,可以使用线程同步机制,如锁(Lock)、信号量(Semaphore)等。
import threading
lock = threading.Lock()
def worker():
with lock:
print("Worker thread is running")
thread1 = threading.Thread(target=worker)
thread2 = threading.Thread(target=worker)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
线程间通信
线程间通信可以通过队列(Queue)来实现。队列是线程安全的,可以在多个线程之间安全地传递数据。
import threading
import queue
def producer(q):
for i in range(5):
q.put(i)
print(f"Produced {i}")
def consumer(q):
while not q.empty():
item = q.get()
print(f"Consumed {item}")
q = queue.Queue()
thread1 = threading.Thread(target=producer, args=(q,))
thread2 = threading.Thread(target=consumer, args=(q,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
线程池
Python 的 concurrent.futures 模块提供了线程池(ThreadPoolExecutor),可以方便地管理多个线程。
from concurrent.futures import ThreadPoolExecutor
def worker(n):
print(f"Worker {n} is running")
with ThreadPoolExecutor(max_workers=3) as executor:
for i in range(5):
executor.submit(worker, i)
注意事项
- GIL(全局解释器锁):Python 的 GIL 限制了同一时间只能有一个线程执行 Python 字节码,因此在 CPU 密集型任务中,多线程可能不会带来性能提升。
- 线程安全:在多线程编程中,确保共享资源的线程安全是非常重要的。
- 线程的生命周期:合理管理线程的启动、运行和结束,避免资源泄漏。
总结
多线程编程是 Python 并发编程的重要部分,适用于 I/O 密集型任务。通过合理使用线程同步机制和线程池,可以有效地提高程序的并发性能。
