I want to count how many elements have ever been putted into multiprocessing.Queue. my implementation is by subclassing multiprocessing.Queue:
import multiprocessing
from multiprocessing.queues import Queue
class QueueFPS(Queue):
def __init__(self, maxsize=200):
self.frame_count = 0
ctx = multiprocessing.get_context()
super().__init__(maxsize, ctx=ctx)
def put(self,*args, **kwargs):
self.frame_count += 1
print("count in put function: ", self.frame_count)
super().put(*args, **kwargs)
def get_count(self):
print("count in get_count: ", self.frame_count)
But when I use this class, I found that the get_count() method always return 0 if I run it with multi process:
def worker(test_queue):
for i in range(2):
test_queue.put("A")
def test_multi_process():
test_queue = QueueFPS()
test_process = multiprocessing.Process(
target=worker,
args=(test_queue,))
test_process.start()
test_process.join()
test_queue.close()
test_queue.join_thread()
print(test_queue.get_count())
the out put is:
count in put function: 1
count in put function: 2
count in get_count: 0
if I run it with only one process, it works as expected, but it will raise a exception(I omit some output of exception)
def test_single_process():
test_queue = QueueFPS()
for i in range(2):
test_queue.put("A")
print(test_queue.get_count())
the output is:
count in put function: 1
count in put function: 2
count in get_count: 2
None
>>> Traceback (most recent call last):
(I omit some output here)
BrokenPipeError: [Errno 32] Broken pipe