gpt4 book ai didi

python - 如何在 Python2.7.10 中使用 multiprocessing 创建子进程而不让子进程与父进程共享资源?

转载 作者:太空宇宙 更新时间:2023-11-03 11:38:12 24 4
gpt4 key购买 nike

我们正在尝试将我们的 python 2.7.10 代码库从 Windows 迁移到 Linux。我们最近发现 Python 2.7 中的多处理库在 Windows 和 Linux 上的行为不同。我们发现了很多文章,例如 this one然而,在描述问题时,我们无法在线找到适用于 Python 2.7 的解决方案。 This is a fix然而,对于 Python 3.4 中的这个问题,我们无法升级到 Python 3.4。有什么方法可以在 Linux 上的 Python 2.7 中使用多处理而无需子进程和父进程共享内存?我们还可以使用修改指南 forking.py python 2.7 中的代码,以确保子进程和父进程不共享内存并执行写时复制。谢谢!

最佳答案

一个可能的解决方案是使用 loky ,一个在 python2.7 中使用 fork-exec 实现 Process 的库。 fork-exec 启动方法的行为与 spawn 类似,在新生成的进程中有一个新的解释器。该库主要用于提供 concurrent.futures API,但您可以使用 mp = loky.backend.get_context() 获取与 multiprocessing< 相同的 API/.

from loky.backend import get_context
import multiprocessing as mp


def child_without_os():
print("Hello from {}".format(os.getpid()))


def child_with_os():
import os
print("Hello from {}".format(os.getpid()))


if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser('Test loky backend')
parser.add_argument('--use-fork', action="store_true",
help="Use start_method='fork' instead of 'loky'")
parser.add_argument('--with-os', action="store_true",
help='Import os module in the child interpreter')
args = parser.parse_args()

# Only import os in the main module, this should fail if the interpreter is
# not shared
import os
print("Main is {}".format(os.getpid()))
if args.use_fork:
ctx = mp
print("Using fork context")
else:
ctx = get_context('loky_init_main')
print("Using loky context")

if args.with_os:
target = child_with_os
else:
target = child_without_os

p = ctx.Process(target=target)
p.start()
p.join()

这给出了

# Use the default context, the child process has a copy-on-write interpreter
# state and can use the os module.
$ python2 test.py --use-fork
Main is 14630
Using fork context
Hello from 14633


# Use the loky context, the child process has a fresh interpreter
# state and need to import the os module.
$ python2 test.py
Main is 14661
Using loky context
Process LokyInitMainProcess-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 267, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/home/tom/Work/prog/loky/test.py", line 6, in child_without_os
print("Hello from {}".format(os.getpid()))
NameError: global name 'os' is not defined


# Now using the correct child function which import the os module
$ python2 test.py --with-os
Main is 14700
Using loky context
Hello from 14705

(免责声明:我是 loky 的维护者之一)。

关于python - 如何在 Python2.7.10 中使用 multiprocessing 创建子进程而不让子进程与父进程共享资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55168149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com