Python3 多处理终止与终止与关闭

Python3 multiprocessing terminate vs kill vs close

我明白 terminatekill 的作用。 close() 是做什么的?

这里引用自 python 文档:

Close the Process object, releasing all resources associated with it. ValueError is raised if the underlying process is still running. Once close() returns successfully, most other methods and attributes of the Process object will raise ValueError.

在我看来,这是有史以来最无用的电话:

会不会是这个文档条目非常尴尬,不知何故它确实意味着 close() 有权终止线程,但它只在某些 python 定义的情况下才这样做检查站?

The issue that added that method 说明:

multiprocessing.Process (actually, the _popen object attached to it) has a GC-based finalizer to release system resources (such as fds). However, it would be nice to be able to release those resources in a timely manner. Adding a close() method would let users do that.

基本上,如果没有 close,某些资源(用于与父级通信的文件描述符,sentinel 句柄,你有什么)只有在 Process 是垃圾时才会关闭收集,在非 CPython 解释器上,甚至在引用循环的情况下是 CPython,可能会在未来某个不确定的时间发生。

close的存在让你可以确保资源在特定时间点确实被清理,因此,例如,启动许多Processes的进程可以确保文件描述符及时清理以防止 运行 进入 ulimit 或内核强加的文件描述符限制。

正常的用例是在 .join()(或 .kill().terminate())之后立即调用 .close()Process 最终 释放资源,即使您不这样做,但它可能不会立即发生。