首页 > 解决方案 > 为什么在 Python 多处理子进程上调用 .join() 会尝试关闭 IDLE shell?

问题描述

以下python脚本:

import multiprocessing as mp

def f():
    return None

def main():
    print('create')
    p = mp.Process(target=f)
    print('start')
    p.start()
    print('join')
    p.join()
    print('done')

if __name__ == '__main__':
    main()

在 Python IDLE 中产生以下输出:

Python 3.7.6 (default, Jan 30 2020, 09:44:41) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
===================== RESTART: /home/user/Desktop/test.py =====================
create
start
join

随后是一个(出乎意料的!)GUI 提示“你的程序仍在运行!你想杀死它吗?”

任何线索这里发生了什么?我知道在 IDLE 中从子进程打印很复杂,但这似乎无关紧要。

请注意,从终端运行相同的代码会给出“正常”输出,并正常退出:

[user@localhost Desktop]$ python test.py 
create
start
join
done
[user@localhost Desktop]$ python --version
Python 3.7.6
[user@localhost Desktop]$ 

在同事的建议下,我尝试添加mp.set_start_method('spawn')if __name__ == '__main__':块中:

import multiprocessing as mp

def f():
    return None

def main():
    mp.set_start_method('spawn')
    print('create')
    p = mp.Process(target=f)
    print('start')
    p.start()
    print('join')
    p.join()
    print('done')

if __name__ == '__main__':
    main()

这导致 IDLE 表现得像我希望的那样:

Python 3.7.6 (default, Jan 30 2020, 09:44:41) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
===================== RESTART: /home/user/Desktop/test.py =====================
create
start
join
done
>>> 

标签: pythonmultiprocessingpython-multiprocessingpython-idle

解决方案


推荐阅读