python - With 子句用于 Python 中的多处理

标签 python python-3.x multiprocessing with-statement

在 python 3 中,您现在可以像这样使用 with 子句安全地打开文件:

with open("stuff.txt") as f:
    data = f.read()

使用这种方法,我不需要担心关闭连接

我想知道我是否可以为多处理做同样的事情。例如,我当前的代码如下所示:

pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
pool.starmap(function,list)
pool.close()
pool.join()

有什么方法可以使用 with 子句来简化它吗?

最佳答案

with multiprocessing.Pool( ... ) as pool:
    pool.starmap( ... )

https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool

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().

您可以在 Pool 部分的底部看到一个示例。

关于python - With 子句用于 Python 中的多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718546/

相关文章:

python - 单字节异或密码(python)

python - Peewee 原子更新复杂逻辑

python - Numpy 随机数生成在矢量化后运行速度变慢

Python filter() 带有变量的对象列表

python - 如何在 fasta 文件中并行计算,其中每个处理器处理一个序列

multithreading - 计算最小值的最短时间

python - 在 Vagrantfile 中安装 PyEnv

Python:如何使用来自不同类的属性

python - networkx 图中的节点间距问题

python - 当子进程工作时做一些事情?