【发布时间】:2021-11-09 12:00:01
【问题描述】:
我试图用multiprocessing.Queue来保存multiprocessing.Process的返回值:
queue = Queue()
for i, (name, func) in enumerate(funcs.items()):
p = Process(target=analyse, args=(i, name, func, grid, queue))
问题是Queue.qsize在macOS上不起作用,所以我使用this answer中的实现。
class Queue(multiprocessing.queues.Queue):
""" A portable implementation of multiprocessing.Queue.
Because of multithreading / multiprocessing semantics, Queue.qsize() may
raise the NotImplementedError exception on Unix platforms like Mac OS X
where sem_getvalue() is not implemented. This subclass addresses this
problem by using a synchronized shared counter (initialized to zero) and
increasing / decreasing its value every time the put() and get() methods
are called, respectively. This not only prevents NotImplementedError from
being raised, but also allows us to implement a reliable version of both
qsize() and empty().
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, ctx=multiprocessing.get_context())
self.size = SharedCounter(0)
def put(self, *args, **kwargs):
self.size.increment(1)
super().put(*args, **kwargs)
注意添加ctx=multiprocessing.get_context()是为了修复缺失的ctx,根据this answer.
有问题的代码:
def analyse(i, name, func, grid, queue):
...
queue.put((i, name, single, minimum, current, peak))
还有 Python 的抱怨:
Traceback (most recent call last):
File "/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "...", line 26, in analyse
queue.put((i, name, single, minimum, current, peak))
File "...", line 48, in put
self.size.increment(1)
AttributeError: 'Queue' object has no attribute 'size'
任何想法错误在哪里?尝试在 PyCharm 中调试,queue 在传递给multiprocessing.Process 时仍然有size,但在analyse() 中调用queue.put() 时它不再存在。
编辑:随意回答这个问题。然而,我放弃了Queue,转而使用multiprocessing.Manager,牺牲了一些宝贵的毫秒时间。
【问题讨论】:
-
我尝试了简化版本(在 Linux 上),但无法复制您的问题?
-
好的,现在我在 macOS 和 Windows 上也看到了。
-
我一直有同样的问题,现在放弃了两次。我正在尝试使我的代码在 Linux/MacOS 上运行,但无法使 mac 版本运行。
标签: python python-multiprocessing