Python 多处理队列 NotImplementedError macOS

10 python macos python-multiprocessing

系统信息

  • 蟒蛇3.8.7
  • 操作系统 11.1(大苏尔)
  • Python 通过以下方式安装brew install python@3.8

要在 Big Sur 和最可能的旧版本上重现:

import multiprocessing as mp


if __name__ == '__main__':
    exp_queue = mp.Queue()
    print(exp_queue.qsize())
Run Code Online (Sandbox Code Playgroud)

结果是:

  File "/Users/username/Library/Application Support/JetBrains/PyCharm2020.3/scratches/scratch.py", line 5, in <module>
    print(exp_queue.qsize())
  File "/usr/local/Cellar/python@3.8/3.8.7/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/queues.py", line 120, in qsize
    return self._maxsize - self._sem._semlock._get_value()
NotImplementedError
Run Code Online (Sandbox Code Playgroud)

看起来写这篇文章的人都multiprocessing/queues.py line 120知道这个问题,但我在某处找不到解决方案:

def qsize(self):
    # Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
    return self._maxsize - self._sem._semlock._get_value()
Run Code Online (Sandbox Code Playgroud)

Arm*_*man 3

正如 V\xc3\xadctor Terr\xc3\xb3n 在 GitHub 讨论中建议的那样,您可以使用他的实现:

\n

https://github.com/vterron/lemon/blob/d60576bec2ad5d1d5043bcb3111dff1fcb58a8d6/methods.py#L536-L573

\n

根据文档:

\n
\n

multiprocessing.Queue 的可移植实现。\n由于多线程/多处理语义,Queue.qsize() 可能\n在未实现 sem_getvalue() 的 Unix 平台(如 Mac OS X)上引发 NotImplementedError 异常。该子类通过使用同步共享计数器(初始化为零)并在每次调用 put() 和 get() 方法时分别增加/减少其值来解决此问题。这不仅可以防止引发NotImplementedError,而且还允许我们实现qsize() 和empty() 的可靠版本。

\n
\n

  • 对于发现此内容的任何人,请注意 Víctor Terrón 的 Queue 实现是根据 GPL 许可的,这意味着如果您的代码没有获得 GPL 许可,则无法在代码中使用它。 (5认同)