使用 with for python 多处理池的目的

Purpose of using with for python multiprocessing pool

我一直在学习 python 中的多进程模块,我注意到 documentation 他们使用 Pool ...

with Pool(processes=4) as pool: pool.map(function,item) 对比

pool=Pool(4) pool.map(function,item)

但在我看到的所有示例和练习中,我一直在使用 pool=Pool(#)。 with 的区别和目的是什么。我知道 with 是 used to wrap the execution of a block with methods defined by a context manager 但它对 Pool 有什么作用。我想我只是不了解 Pool。

with 在 python 中用于上下文管理。

与 pool 一起使用时,相当于在 map 或 apply 方法之后调用 pool.close()。 如果不调用,您最终会在您的机器上遇到大量的幽灵进程。

另一个例子是在处理文件时使用 with ,因此隐式调用 f.close()

It just implicitly calls the close method:

New in version 3.3: Connection objects now support the context management protocol – see Context Manager Types. __enter__() returns the connection object, and __exit__() calls close().

如果您阅读 multiprocessing.pools.Pool class 的源代码,您会发现它有:

def __exit__(self, exc_type, exc_val, exc_tb):
    self.terminate()

所以它只是在上下文管理器结束时为您调用 terminate() 方法。

terminate() 方法在未完成未完成的工作的情况下立即停止工作进程,而 close() 方法仅阻止将更多任务提交到池中。

来自documentation:

New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types. __enter__() returns the pool object, and __exit__() calls terminate().