繁体   English   中英

Python 多处理卡住

[英]Python multiprocessing gets stuck

我对 Python 和多处理完全陌生,我在网上找到了一些教程来帮助我理解多处理 package。

我的代码有一组使用 RungeKutta4 方法的微分方程,我需要在不同的起始条件下运行大量计算。

代码本身可以工作,但如果没有多重处理,它需要很长时间才能完成,我认为使用并行化可能是理想的,因为计算是独立的......

我正在使用 Anaconda 作为 IDE 顺便说一句..

所以我用

import multiprocessing as mp
iterations = np.arange(start,end,step)
pool = mp.Pool(mp.cpu_count())                           # Step 1: Init multiprocessing.Pool()
results = pool.map(rungeKutta4, [k for k in iterations]) # Step 2: apply pool map              
pool.close()                                             # Step 3: close

当我在 Anaconda 中运行它时,我没有收到错误,它开始计算但它永远不会停止......我在哪里 go 错了?

提前感谢您的帮助...

最好的

编辑:我在这里添加了整个代码......

# Python program to implement Runge Kutta method 
# Markus Schmid
# 2020 Appalachian State University
# jupyter nbconvert --to python FILENAME.ipynb

# y" + 2*beta*y' + w0*sin(y) = A + B*cos(w*t)
# Import used libraries
import numpy as np
import math
import matplotlib.pyplot as plt
import time
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
import multiprocessing as mp
print("Number of processors: ", mp.cpu_count())
# list for time (x axis) and result (y axis)
result = []
w0 = 10                  # undamped angular frequency of the oscillator
beta = 1
B = 1
A = 0
B = 10
w = 4
theta_init = 0
theta_end = 20
theta_step = 0.1

# initial conditions
t0 = 0
y0 = 0
z0 = 0
t_final = 20                   # final time
h = 0.01                    # fixed step size
n = (int)((t_final - t0)/h)   # datapoints per RK4 iteration

# define functions
def funcf(t, y, z): 
    return (z)
def funcg(t, y, z): 
    return (A+B*math.cos(w*t) - 2*beta*z - w0*math.sin(y))

# Finds value of y for a given x using step size h 
# and initial value y0 at x0. 
def rungeKutta4(y): 
    # Count number of iterations using step size or 
    # step height h 
    t = t0
    z = z0
    n = (int)((t_final - t)/h)  
    for i in range(1, n + 1): 
        # Apply Runge Kutta to find next value of y
        k1 = h * funcf(t, y, z) 
        l1 = h * funcg(t, y, z)  

        k2 = h * funcf(t + 0.5 * h, y + 0.5 * k1, z + 0.5 * l1) 
        l2 = h * funcg(t + 0.5 * h, y + 0.5 * k1, z + 0.5 * l1)  

        k3 = h * funcf(t + 0.5 * h, y + 0.5 * k2, z + 0.5 * l2) 
        l3 = h * funcg(t + 0.5 * h, y + 0.5 * k2, z + 0.5 * l2) 

        k4 = h * funcf(t + h, y + k3, z + l3) 
        l4 = h * funcg(t + h, y + k3, z + l3) 

        # Update next value of y 
        y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4) 
        z = z + (1.0 / 6.0)*(l1 + 2 * l2 + 2 * l3 + l4) 

        #result.append(y)                
        t = t + h # Update next value of t
    return y 

iterations = np.arange(theta_init,theta_end+theta_step,theta_step)   # number iterations for omega sweep

start_time = time.time()
#for k in iterations:     # for serial calculation
#            rungeKutta4(k)
pool = mp.Pool(mp.cpu_count()) # Step 1: Init multiprocessing.Pool()
results = pool.map(rungeKutta4, [k for k in iterations]) # Step 2: apply pool map        
end_time = time.time()            
pool.close()  # Step 3: close
print ("The program took", end_time - start_time, "s to run")

#table = np.array(result).reshape(len(iterations),n)   # rearrange array, 1 row is const. theta0
timer = np.arange(t0,t_final,h) # time array

您的代码看起来不错,它适用于我(Ipython 和 python3.6.9),我在下面附上了结果和配置。

您是否尝试在不同的python 虚拟环境(Anaconda 之外)中运行它? 如前所述(在 Ronald 的评论中), 其他 IDE存在 python 的多处理错误,请尝试使用命令行/Ipython 运行它。 我以前甚至在vscode中也遇到过

配置:

蟒蛇配置

结果:

脚本结果

我最初的评论:

IDE 可以以意想不到的方式与 Python 交互。 在 stackoverflow 上的 IDE 中多次提到多处理行为不端。 因此,最好通过从 shell(ms-windows 上的 cmd.exe)直接调用 Python 来测试您的脚本。

你回复:

RuntimeError:在当前进程完成其引导阶段之前,已尝试启动新进程。

为了使multiprocessing在 ms-windows 上正常工作,您必须能够在脚本中导入代码而不会产生副作用,例如启动新进程

这意味着您必须将除了导入和函数/类定义之外的所有内容都放在一个主块中,就像这个受文档启发的示例一样:

from multiprocessing import Process

def foo():
    print('hello')

if __name__ == '__main__':
    p = Process(target=foo)
    p.start()

基本上,ms-windows 缺少类 UNIX 系统上存在的漂亮的fork()系统调用。 因此,Python 开发人员必须想出一个巧妙的技巧来让multiprocessing处理在 ms-windows 上工作。 有关血腥细节,请参见例如此答案

编辑在 ms-windows 上,似乎还需要将 worker function 放在自己的文件中并导入。 参见例如这里

我找到了使它在 Anaconda 中工作的解决方案。

除了

if __name__ == '__main__':

被称为(工作人员)的 function 必须在其 own.py 文件中,该文件必须在开始时导入。

我将 RK4 放在我一开始导入的 RK4.py 文件中,但它不起作用,但在我的情况下,来回传递值会带来新的问题......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM