Python提供了对多线程和多进程的支持,但使用它们时需要注意一些关键区别和限制。
-
多线程:Python的标准库
threading
提供了多线程支持。由于Python的全局解释器锁(GIL)的存在,Python的多线程在大多数情况下并不能实现真正的并行计算,但它仍然可以用于执行I/O密集型任务,如文件读写、网络通信等。
python复制代码
import threading | |
def worker(num): | |
"""线程函数""" | |
print(f"Worker {num}") | |
# 创建线程列表 | |
threads = [] | |
for i in range(5): | |
t = threading.Thread(target=worker, args=(i,)) | |
threads.append(t) | |
t.start() | |
# 等待所有线程完成 | |
for t in threads: | |
t.join() |
-
多进程:Python的
multiprocessing
模块提供了多进程支持。与多线程不同,多进程可以实现真正的并行计算,因为每个进程都有自己的解释器,不受GIL的限制。
python复制代码
import multiprocessing | |
def worker(num): | |
"""进程函数""" | |
print(f"Worker {num}") | |
# 创建进程列表 | |
processes = [] | |
for i in range(5): | |
p = multiprocessing.Process(target=worker, args=(i,)) | |
processes.append(p) | |
p.start() | |
# 等待所有进程完成 | |
for p in processes: | |
p.join() |
需要注意的是,虽然多进程可以实现并行计算,但它通常比多线程消耗更多的资源。因此,在选择使用多线程还是多进程时,需要根据具体的应用场景和需求来权衡。
另外,对于计算密集型任务,如果需要在多个核心上并行执行,通常会选择使用多进程。而对于I/O密集型任务,多线程通常是一个更好的选择,因为它们可以在一个核心上交替执行,从而充分利用I/O等待时间。