Python 多线程
Python 多线程基础概念
多线程允许程序在同一时间执行多个任务,适用于 I/O 密集型任务(如网络请求、文件读写)或需要并行处理的场景。Python 通过 threading
模块实现多线程,但由于全局解释器锁(GIL)的存在,多线程在 CPU 密集型任务中性能提升有限。
创建线程的两种方法
方法一:继承 threading.Thread
类
import threadingclass MyThread(threading.Thread):def __init__(self, thread_id, name):threading.Thread.__init__(self)self.thread_id = thread_idself.name = namedef run(self):print(f"线程 {self.name} 正在运行")# 创建线程实例
thread1 = MyThread(1, "Thread-1")
thread2 = MyThread(2, "Thread-2")# 启动线程
thread1.start()
thread2.start()# 等待线程结束
thread1.join()
thread2.join()
print("主线程退出")
方法二:直接使用 threading.Thread
构造函数
import threadingdef worker(name):print(f"线程 {name} 正在执行")# 创建线程
threads = []
for i in range(3):t = threading.Thread(target=worker, args=(f"Thread-{i}",))threads.append(t)t.start()# 等待所有线程完成
for t in threads:t.join()
print("所有线程执行完毕")
线程同步与锁机制
多线程共享全局变量时可能导致数据竞争,需使用锁(Lock
)确保线程安全:
import threadingcounter = 0
lock = threading.Lock()def increment():global counterfor _ in range(100000):lock.acquire()counter += 1lock.release()threads = []
for _ in range(2):t = threading.Thread(target=increment)threads.append(t)t.start()for t in threads:t.join()
print(f"最终计数器值: {counter}") # 正确输出 200000
线程间通信
通过 Queue
模块实现线程安全的数据交换:
import threading
import queue
import timedef producer(q):for i in range(5):time.sleep(1)q.put(f"产品 {i}")print(f"生产了 产品 {i}")def consumer(q):while True:item = q.get()if item is None:breakprint(f"消费了 {item}")q.task_done()q = queue.Queue()
producer_thread = threading.Thread(target=producer, args=(q,))
consumer_thread = threading.Thread(target=consumer, args=(q,))producer_thread.start()
consumer_thread.start()producer_thread.join()
q.put(None) # 发送结束信号
consumer_thread.join()
线程池与高级用法
使用 concurrent.futures
简化线程管理:
from concurrent.futures import ThreadPoolExecutor
import urllib.requestdef download_url(url):with urllib.request.urlopen(url) as response:return f"{url}: {len(response.read())} 字节"urls = ["https://www.python.org","https://www.google.com","https://www.github.com"
]with ThreadPoolExecutor(max_workers=3) as executor:results = executor.map(download_url, urls)for result in results:print(result)
多线程与性能优化
GIL 的影响:
Python 的全局解释器锁(GIL)确保同一时间只有一个线程执行字节码。对于 CPU 密集型任务,多线程可能无法提升性能,此时建议使用多进程(multiprocessing
模块)。
适用场景对比:
- 多线程:I/O 阻塞操作(如网络请求、文件读写)
- 多进程:CPU 密集型计算(如数学运算、图像处理)
可视化示例
以下是一个简单的多线程执行流程图:
主线程
│
├─ 启动 Thread-1
│ └─ 执行任务 A
├─ 启动 Thread-2
│ └─ 执行任务 B
└─ 等待所有线程结束
完整代码示例
import threading
import timedef task(name, delay):print(f"任务 {name} 开始")time.sleep(delay)print(f"任务 {name} 完成")# 创建并启动线程
threads = [threading.Thread(target=task, args=("A", 2)),threading.Thread(target=task, args=("B", 1)),threading.Thread(target=task, args=("C", 3))
]for t in threads:t.start()# 等待线程结束
for t in threads:t.join()print("所有任务执行完毕")
注意事项
- 避免死锁:确保锁的获取和释放成对出现。
- 线程安全:使用
Queue
或Lock
保护共享资源。 - 异常处理:线程内的异常需在线程内捕获,否则会静默失败。
通过合理设计,多线程能显著提升程序响应速度,尤其是在涉及等待外部资源的场景中