我们正在尝试将python 2.7.10代码库从Windows迁移到Linux。我们最近发现,Python2.7中的多处理库在Windows和Linux上的行为不同。我们已经找到了许多像this one这样的文章来描述这个问题,然而,我们无法在网上找到Python2.7的解决方案。This is a fix对于Python3.4中的这个问题,我们无法升级到Python3.4。有没有办法在Linux上使用Python2.7中的多进程而不让子进程和父进程共享内存?我们还可以使用Python2.7中修改forking.py代码的指南来确保子进程和父进程不共享内存和执行写入时复制。谢谢!
发布于 2019-03-15 15:18:29
一种可能的解决方案是使用loky,这是一个在python2.7中提供带有fork-exec的Process实现的库。fork-exec start方法的行为类似于派生,在新派生的进程中有一个新的解释器。该库主要用于提供concurrent.futures接口,但您也可以使用mp = loky.backend.get_context()来获得与multiprocessing相同的接口。
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的维护者之一)。
发布于 2019-03-15 03:39:08
如您所知,CPython错误跟踪器中的补丁不能很好地应用于Python2.7的多处理版本,并且这些补丁包含一些用于semaphore.c的额外功能,以便在以后正确清理信号量。
我认为你最好的办法是从Python3移植多处理模块,复制Python代码,将其重命名为processing,发现缺少的C特性并解决它们(例如,清理自己的信号量或不使用它们)。尽管这个库很大,但只移植您使用的特性可能是很简单的。如果你能够发布backport,我相信很多人都会对这个项目感兴趣。
根据您对多处理的依赖程度,一种不同的选择是通过使用subprocess模块运行sys.executable来运行更多的Python。
https://stackoverflow.com/questions/55168149
复制相似问题