Python 3.8引入了新的共享内存特性。我们尝试使用SharedMemoryManager
,但出现了NameError
错误。
我认为可能是在我们复杂的场景中做错了什么,因此我使用Python文档片段对其进行了分解。
try:
# python >= 3.8
from multiprocessing.managers import SharedMemoryManager as Manager
except:
# python < 3.8
from multiprocessing.managers import BaseManager as Manager
class MathsClass:
def add(self, x, y):
return x + y
def mul(self, x, y):
return x * y
class MyManager(Manager):
pass
MyManager.register('Maths', MathsClass)
if __name__ == '__main__':
with MyManager() as manager:
maths = manager.Maths()
print(maths.add(4, 3)) # prints 7
print(maths.mul(7, 8)) # prints 56
这基本上是从多进程文档中提取的(除了回退导入),在Python 3.7中工作正常,但在Python 3.8中会产生以下错误:
Traceback (most recent call last):
File "scripts/debug_shared_memory_issue.py", line 21, in <module>
maths = manager.Maths()
File "/usr/lib/python3.8/multiprocessing/managers.py", line 740, in temp
token, exp = self._create(typeid, *args, **kwds)
File "/usr/lib/python3.8/multiprocessing/managers.py", line 625, in _create
id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds)
File "/usr/lib/python3.8/multiprocessing/managers.py", line 91, in dispatch
raise convert_to_error(kind, result)
multiprocessing.managers.RemoteError:
---------------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.8/multiprocessing/managers.py", line 210, in handle_request
result = func(c, *args, **kwds)
File "/usr/lib/python3.8/multiprocessing/managers.py", line 1312, in create
if hasattr(self.registry[typeid][-1], "_shared_memory_proxy"):
NameError: name 'self' is not defined
---------------------------------------------------------------------------
Python 3.8的发布说明和文档中提到
SharedMemoryManager
是"BaseManager的子类",因此我们期望它可以作为一种即插即用的替代方案。但事实并非如此。在查看当前的CPython 3.8分支时,似乎没有相关的更改。然而,在Python 3.9中,create
函数有一个显式的self
参数。但是3.9还在进行中,因此我们不想在生产软件中使用它。谢谢您的帮助!