绘图时多处理不工作

Multiprocessing not working while plotting

好的,我正在尝试使用多处理同时遍历两条路径(路径 1 和路径 2)。但是路径并没有在图中绘制在一起,它们是一个接一个地绘制的。请让我知道如何在图中同时遍历两条路径?这是我的代码:

import os
import sys
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
import threading
from multiprocessing import Process
do_animation = True

def visualize_path(grid_map, start, goal, path):  # pragma: no cover
    oy, ox = start
    gy, gx = goal
    px, py = np.transpose(np.flipud(np.fliplr(path)))
    if not do_animation:
        plt.imshow(grid_map, cmap='Greys')
        plt.plot(ox, oy, "-xy")
        plt.plot(px, py, "-r")
        plt.plot(gx, gy, "-pg")
        plt.show()
    else:
        for ipx, ipy in zip(px, py):
            plt.cla()
            # for stopping simulation with the esc key.
            plt.gcf().canvas.mpl_connect(
                'key_release_event',
                lambda event: [exit(0) if event.key == 'escape' else None])
            plt.imshow(grid_map, cmap='Greys')
            plt.plot(ox, oy, "-xb")
            plt.plot(px, py, "-r")
            plt.plot(gx, gy, "-pg")
            plt.plot(ipx, ipy, "or")
            plt.axis("equal")
            plt.grid(True)
            plt.pause(0.5)

def main():
    start = [0,0]
    goal = [20,20]
    path1 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
    path2 = [[7, 15], [8, 16], [9, 17], [10, 18], [11, 19], [12, 20]]
    grid = [[0.0 for i in range(20)] for j in range(20)]
    print(grid)
    print(path1)
    print(path2)
    Process(target=visualize_path(grid, start, goal, path1)).start()
    Process(target=visualize_path(grid, start, goal, path2)).start()

if __name__ == "__main__":
    main()

您根本没有进行多处理。您正在从主进程调用 visualize_path(grid, start, goal, path1) 并将其 return 值传递给 Process 构造函数,即 None ,然后才执行下一个 Process构造函数并做同样的事情。你要做的是:

    Process(target=visualize_path, args=(grid, start, goal, path1)).start()
    Process(target=visualize_path, args=(grid, start, goal, path2)).start()

或:

    p1 = Process(target=visualize_path, args=(grid, start, goal, path1))
    p2 = Process(target=visualize_path, args=(grid, start, goal, path2))
    p1.start()
    p2.start()
    # Explicitly wait for the processes to complete:
    p1.join()
    p2.join()

但是您正在创建单独的进程,每个进程 运行 在它们自己的地址 space 中,并且每个进程都将创建自己的独立图 -- 尽管现在这将并行发生。但是,如果这是您的意图,您似乎不能在 相同的 绘图上绘制两个单独的进程。