ValueError: Cannot close a process while it is still running. You should first call join() or termin

ValueError: Cannot close a process while it is still running. You should first call join() or terminate().

if __name__ == '__main__':
    while True:
        # process = multiprocessing.Process(target=run)
        # process.start()
        # process.join()
        process = multiprocessing.Process(target=run_buchong)
        process.daemon=True
        process.start()
        process.close()
        process.join()
Traceback (most recent call last):
  File "E:/BaiduSyncdisk/shellcompany/shell/shell/anjuke3/anjuke_def.py", line 678, in <module>
    process.close()
  File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 181, in close
    raise ValueError("Cannot close a process while it is still running. "
ValueError: Cannot close a process while it is still running. You should first call join() or terminate().

原因分析

当使用多进程执行任务时,如果在不正确地关闭进程之前尝试退出程序,则可能会收到 ValueError: Cannot close a process while it is still running. You should first call join() or terminate() 这样的错误消息。这是因为某个子进程仍在运行并且主进程需要等待其完成。

解决此错误的一种方法是在使用完进程之后调用 join()terminate() 方法来显式关闭进程。这将使主进程等待直到子进程完成。

例如,假设我们有一个多进程程序,用于计算一组数的平均值:

from multiprocessing import Pool

def calculate_average(numbers):
    with Pool(processes=2) as pool:
        result = pool.map(sum, numbers)
        avg = sum(result) / len(numbers)
        return avg

if __name__ == '__main__':
    numbers = [[1, 2, 3], [4, 5, 6]]
    calculate_average(numbers)

在这个示例中,我们使用了一个 Pool 对象来并行执行 sum() 函数对每个列表的求和。如果在执行该程序时立即终止,那么将会抛出 ValueError。为了解决这个问题,我们可以在 Pool 对象上调用 close() 方法,然后在调用 join() 方法来等待所有子进程完成执行:

from multiprocessing import Pool

def calculate_average(numbers):
    with Pool(processes=2) as pool:
        result = pool.map(sum, numbers)
        avg = sum(result) / len(numbers)
        pool.close()  # 关闭进程池
        pool.join()   # 等待所有子进程执行完毕
        return avg

if __name__ == '__main__':
    numbers = [[1, 2, 3], [4, 5, 6]]
    calculate_average(numbers)

这个修改能够成功解决问题,在程序执行完成前显示等待所有子进程执行完毕并关闭。

你可能感兴趣的:(python,服务器)