尝试将需要并行运算的函数同并行运算结构体分开进行并行运算。
例:
- 创建一个名为
calculate.py
的新文件,并将以下代码粘贴到该文件中:
- def calculate(num):
return num ** 2
- 主程序的代码如下:
-
import multiprocessing
from calculate import calculate
if __name__ == '__main__':
# 要计算的数字列表
numbers = [1, 2, 3, 4, 5]
# 创建进程池
pool = multiprocessing.Pool()
# 在进程池中并行执行任务
results = pool.map(calculate, numbers)
# 关闭进程池,不再接受新任务
pool.close()
# 等待所有子进程完成
pool.join()
# 输出结果
print(results)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)