Section 120.1: 使用 multiprocessing 模块并行化任务
import multiprocessing
def fib(n):
"""为了减缓 CPU 的速度,故意选择了一种低效的计算斐波那契数的方法。"""
if n <= 2:
return 1
else:
return fib(n-1)+fib(n-2)
p = multiprocessing.Pool()
print(p.map(fib,[38,37,36,35,34,33]))
# 输出:[39088169, 24157817, 14930352, 9227465, 5702887, 3524578]

由于每个对 fib 的调用都是并行执行的,因此在双处理器上,整个示例的执行时间比顺序执行快 1.8 倍。
适用于 Python 2.2 及以上版本。
Section 120.2: 使用 C 扩展来并行化任务
这里的想法是将计算密集型任务转移到 C 中(使用特殊宏),独立于 Python,并让 C 代码在工作时释放 GIL。
#include "Python.h"
...
PyObject *pyfunc(PyObject *self, PyObject *args) {
...
Py_BEGIN_ALLOW_THREADS
// Threaded C code
...
Py_END_ALLOW_THREADS
...
}
Section 120.3: 使用父脚本和子脚本并行执行代码
child.py
import time
def main():
print("starting work")
time.sleep(1)
print("work work work work work")
time.sleep(1)
print("done working")
if __name__ == '__main__':
main()
parent.py
import os
def main():
for i in range(5):
os.system("python3 child.py &")
if __name__ == '__main__':
main()

这对于并行、独立的 HTTP 请求/响应任务或数据库的查询/插入操作非常有用。也可以向 child.py 脚本传递命令行参数。通过所有脚本定期检查一个独立的服务器(例如 Redis 实例),可以实现脚本之间的同步。
Section 120.4: 使用 PyPar 模块进行并行化
pypar 库是一个用于并行计算的 Python 库,但需要注意的是,pypar 已经不再维护,且在现代 Python 环境中可能无法正常工作。如果你正在使用较新的 Python 版本,建议使用更现代的并行计算库,例如 MPI for Python(mpi4py),它是基于 MPI(Message Passing Interface)的并行计算库,功能强大且维护良好。
from mpi4py import MPI
# 初始化 MPI 环境
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
ncpus = comm.Get_size()
node = MPI.Get_processor_name()
print(f'I am rank {rank} of {ncpus} on node {node}')
if rank == 0:
msg = 'P0'
comm.send(msg, dest=1)
msg = comm.recv(source=ncpus - 1) # 接收来自最后一个进程的消息
print(f'Processor 0 received message "{msg}" from rank {ncpus - 1}')
else:
source = rank - 1
destination = (rank + 1) % ncpus
msg = comm.recv(source=source)
msg = msg + 'P' + str(rank)
comm.send(msg, dest=destination)
# MPI 环境在程序结束时会自动清理,无需显式调用 finalize()