Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiprocessing Queue NotImplementedError macOS

System information

To reproduce on Big Sur and most probably older versions:

import multiprocessing as mp


if __name__ == '__main__':
    exp_queue = mp.Queue()
    print(exp_queue.qsize())

Results in:

  File "/Users/username/Library/Application Support/JetBrains/PyCharm2020.3/scratches/scratch.py", line 5, in <module>
    print(exp_queue.qsize())
  File "/usr/local/Cellar/[email protected]/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

It looks like whoever wrote this in multiprocessing/queues.py line 120 is aware of the issue, but I can't find a solution somewhere:

def qsize(self):
    # Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
    return self._maxsize - self._sem._semlock._get_value()
like image 684
schissmantics Avatar asked Nov 16 '22 01:11

schissmantics


1 Answers

As Víctor Terrón has suggested in a GitHub discussion, you can use his implementation:

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

According to the doc:

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().

like image 129
Arman Avatar answered Dec 11 '22 03:12

Arman