[英]Python Why must multiprocessing.set_start_method be invoked in the __name__ == '__main__' clause?
If you want to spawn a process, instead of fork a process, using multiprocess
module, you can use the following command:如果要使用
multiprocess
模块生成进程,而不是 fork 进程,可以使用以下命令:
multiprocessing.set_start_method('spawn')
The documentation states:该文档指出:
To select a start method you use the set_start_method() in the if
__name__ == '__main__'
clause of the main module到 select 一个启动方法,您在主模块的 if
__name__ == '__main__'
子句中使用 set_start_method()
However, I've found that I can call set_start_method('spawn')
outside of the if __name__ == '__main__'
clause, and it still spawns instead of forks processes on Unix.但是,我发现我可以在
if __name__ == '__main__'
子句之外调用set_start_method('spawn')
,它仍然会在 Unix 上生成而不是派生进程。
In fact, as long as you invoke set_start_method('spawn')
prior to the first invocation of multiprocessing.Process()
, it will behave as expected.事实上,只要您在第一次调用
multiprocessing.Process()
set_start_method('spawn')
,它就会按预期运行。 If you instead attempt to call set_start_method('spawn')
after the first multiprocessing.Process()
, it seems to be ignored and will fork instead of spawn.如果您尝试在第一个
multiprocessing.Process()
之后调用set_start_method('spawn')
,它似乎会被忽略并且会分叉而不是生成。
Why does the documentation state that set_start_method
should be invoked inside the if __name__ == '__main__'
clause?为什么文档
set_start_method
应该在if __name__ == '__main__'
子句中调用 set_start_method?
Sub-processes do not enter the if __name__ == '__main__'
clause.子流程不输入
if __name__ == '__main__'
子句。 That way we can guarantee set_start_method
will be called only once.这样我们就可以保证
set_start_method
只会被调用一次。
It does not need to be specifically at the module level, but it can be in any function that is ran through that clause, and still guarantee only one invocation.它不需要特别在模块级别,但它可以在通过该子句的任何 function 中,并且仍然保证只调用一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.