python - 绘图时多重处理不起作用

标签 python python-3.x multithreading python-requests multiprocessing

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

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) 并将其返回值传递给 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()

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

关于python - 绘图时多重处理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69006074/

相关文章:

python - Jupyter 笔记本 : connection to kernel restarts infinitely

python - 在 Pandas 中用 NaN 替换多列中的多个字符串和数字

Python 正则表达式部分不区分大小写

python - 使用线程时不触发 Pyttsx3 回调

Python 日志记录 : Create new log file if it is deleted while program is running (RotatingFileHandler)

python - python中的for循环不操作原始对象,而是执行深复制

c++ - 为什么必须显式加入线程?

python - 线程错误 : AttributeError: 'NoneType' object has no attribute '_initialized'

java - Jsch SFTP 客户端无法创建新的 native 线程

c - 为什么 sigwait() 是 MT 安全的而 sigsuspend() 不是?