如何在 Python 中对单个函数执行多处理?
How to perform multiprocessing for a single function in Python?
我正在阅读 Python 3 的 Multiprocessing 主题并尝试将该方法合并到我的脚本中,但是我收到以下错误:
AttributeError: __ exit __
我将 Windows 7 与 i-7 8 核处理器一起使用,我有一个大型 shapefile,我希望最好使用所有 8 核来处理(使用制图软件 QGIS)。下面是我的代码,我将不胜感激对此事的任何帮助:
from multiprocessing import Process, Pool
def f():
general.runalg("qgis:dissolve", Input, False, 'LAYER_ID', Output)
if __name__ == '__main__':
with Pool(processes=8) as pool:
result = pool.apply_async(f)
multiprocessing.Pool
的上下文管理器功能仅添加到 Python 3.3:
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()
.
__exit__
未定义这一事实表明您使用的是 3.2 或更早版本。您需要在 Pool
上手动调用 terminate
以获得等效行为:
if __name__ == '__main__':
pool = Pool(processes=8)
try:
result = pool.apply_async(f)
finally:
pool.terminate()
就是说,您可能不想在这里使用 terminate
(或 with
语句,通过扩展)。 Pool
的 __exit__
方法调用 terminate
,这将强行退出你的工人,即使他们没有完成他们的工作。您可能想在退出之前实际等待工作人员完成,这意味着您应该改为调用 close()
,然后使用 join
等待所有工作人员完成后再退出:
if __name__ == '__main__':
pool = Pool(processes=8)
result = pool.apply_async(f)
pool.close()
pool.join()
我正在阅读 Python 3 的 Multiprocessing 主题并尝试将该方法合并到我的脚本中,但是我收到以下错误:
AttributeError: __ exit __
我将 Windows 7 与 i-7 8 核处理器一起使用,我有一个大型 shapefile,我希望最好使用所有 8 核来处理(使用制图软件 QGIS)。下面是我的代码,我将不胜感激对此事的任何帮助:
from multiprocessing import Process, Pool
def f():
general.runalg("qgis:dissolve", Input, False, 'LAYER_ID', Output)
if __name__ == '__main__':
with Pool(processes=8) as pool:
result = pool.apply_async(f)
multiprocessing.Pool
的上下文管理器功能仅添加到 Python 3.3:
New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types.
__enter__()
returns the pool object, and__exit__()
callsterminate()
.
__exit__
未定义这一事实表明您使用的是 3.2 或更早版本。您需要在 Pool
上手动调用 terminate
以获得等效行为:
if __name__ == '__main__':
pool = Pool(processes=8)
try:
result = pool.apply_async(f)
finally:
pool.terminate()
就是说,您可能不想在这里使用 terminate
(或 with
语句,通过扩展)。 Pool
的 __exit__
方法调用 terminate
,这将强行退出你的工人,即使他们没有完成他们的工作。您可能想在退出之前实际等待工作人员完成,这意味着您应该改为调用 close()
,然后使用 join
等待所有工作人员完成后再退出:
if __name__ == '__main__':
pool = Pool(processes=8)
result = pool.apply_async(f)
pool.close()
pool.join()