Python中的multiprocessing库问题

2 投票
2 回答
69 浏览
提问于 2025-04-14 16:55

我在使用Python的一个多进程库时遇到了问题。这个库我已经安装好了,我对此很确定。

def foo():
    print("hello")

import multiprocessing as mp

task = mp.Process(target = foo)
task.start()

我本来希望程序能打印出hello,但是它什么都没有输出。

我用pip卸载了这个库,然后又重新安装了一遍,但结果还是没有改变。

2 个回答

0

这里有两件事:

  1. 其他人提到你忘记调用 `join()` 了,并给出了说明。
  2. 你需要把你的代码放在一个 if __name__ 块里面,否则会出现错误。我感觉你可能已经看到了这个错误。它的样子是这样的:
...
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

说到这里,这里有一个修改过的代码版本:

import multiprocessing


def foo():
    print("hello")


if __name__ == "__main__":
    task = multiprocessing.Process(target=foo)
    task.start()
    task.join()
1

你忘了使用 task.join() 了。没有这个 join(),主程序可能会在子进程还没执行完的时候就结束了。

撰写回答