【问题标题】:Python script hangs when getting queue entries after running Process运行 Process 后获取队列条目时 Python 脚本挂起
【发布时间】:2016-01-21 11:41:17
【问题描述】:

我正在尝试学习 Python 3 中的多处理模块。我的玩具问题是 Lennard-Jones 势中粒子轨迹的欧拉积分,我已将其添加到下面的代码块中。

mpSwichFalse 时,函数Integrate 在当前进程中运行,代码按预期执行。否则Integrate 在子进程中运行并且脚本挂起。当我使用调试器逐步执行此操作时,当我尝试使用results.update(outputQueue.get()) 将轨迹从子进程中取出时,似乎发生了挂起。我并不完全相信这是挂起的原因而不是症状,无论哪种方式我都在努力寻找问题的根源。我计划为一个时间步值Dt 运行一个子进程,然后并行运行几个Dt 值。

import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp

# calculate position and momentum
def Integrate(Dt, output):
    T = np.float64(100.0)
    N = np.int(T/Dt)
    q = np.zeros((N, 3))
    p = np.zeros((N, 3))
    q[0, :] = 1.9
    p[0, :] = -0.0001
    LJ = lambda x: x**-12 - 2.0*x**-6
    M = np.float64(45.0)

    # Euler method
    for nn in range(N - 1):
        q[nn + 1, :] = q[nn, :] + Dt*p[nn, :]        
        h = np.abs(q[nn + 1, :] - q[nn, :]) * np.ones(3)
        dphidq = (LJ(q[nn, :] + h) - LJ(q[nn, :] - h))/(2.0*h)    
        p[nn + 1, :] = p[nn, :] - Dt*dphidq/M

    # store results in queue
    outdict = {}
    outdict[Dt] = [q, p]
    output.put(outdict)

# manage simulation
mpSwitch = True
if mpSwitch:
    # launch process to perform simulation
    if __name__ == '__main__':
        outputQueue = mp.Queue()
        p = mp.Process(target = Integrate, args = (np.float64(0.001), outputQueue))
        p.start()

        results = {}
        results.update(outputQueue.get())

        p.join()
else:
    # perform simulation in current process
    outputQueue = mp.Queue()
    Integrate(np.float64(0.001), outputQueue)
    results = {}
    results.update(outputQueue.get())

#plot results
plt.figure(1)
plt.clf()
plt.title('Phase Diagram')
plt.plot(results[0.001][0][:, 0], results[0.001][1][:, 0], '.-')
plt.xlabel('Coordinate')
plt.ylabel('Momentum')

【问题讨论】:

    标签: python-3.x queue multiprocess


    【解决方案1】:

    您是否尝试过使用 concurrent.futures 包中的 ThreadPoolExecutor 并查看是否可以针对同一示例重现该行为?

    【讨论】:

    • 我希望为此使用一些更简单的东西,因为我仍在学习如何使用多处理模块。似乎有很多关于我尝试过的类似示例,但似乎不适用于此问题。
    【解决方案2】:

    这个问题原来是我的一个愚蠢的错误。这是一个范围界定问题,如果将绘图部分移到 if __name__ == '__main__' 语句下,那么此代码似乎可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2018-12-13
      • 2011-09-23
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多