diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst index bd0fc2d8f3c735..c5e743177589fd 100644 --- a/Doc/library/queue.rst +++ b/Doc/library/queue.rst @@ -190,6 +190,17 @@ Example of how to wait for enqueued tasks to be completed:: for t in threads: t.join() +One more method provides information about progress of tasks completion. + +.. method:: Queue.unfinished() + + Return number of unfinished tasks i.e. number of such tasks which were queued but + consumer threads hadn't yet indicated that task is completed (via call of + :meth:`task_done`). + + To get the correct value from this method you have to call :meth:`task_done` + for each call to :meth:`get` used to fetch a task to indicate that the item was + retrieved and all work on it is complete. .. seealso:: diff --git a/Lib/queue.py b/Lib/queue.py index 572425e844c52e..fc2ce3977712f6 100644 --- a/Lib/queue.py +++ b/Lib/queue.py @@ -82,6 +82,13 @@ def join(self): while self.unfinished_tasks: self.all_tasks_done.wait() + def unfinished(self): + '''Return number of unfinished tasks i.e. number of such tasks which + were queued but consumer threads hadn't yet indicated that task is + completed (via call of method task_done()). + ''' + return self.unfinished_tasks + def qsize(self): '''Return the approximate size of the queue (not reliable!).''' with self.mutex: diff --git a/Lib/test/test_queue.py b/Lib/test/test_queue.py index 4ccaa39adff69f..377ebeb188709f 100644 --- a/Lib/test/test_queue.py +++ b/Lib/test/test_queue.py @@ -193,6 +193,15 @@ def test_queue_join(self): else: self.fail("Did not detect task count going negative") + def test_queue_unfinished(self): + q = self.type2test() + q.put(1) + q.put(2) + self.assertEqual(q.unfinished(), 2) + q.get() + q.task_done() + self.assertEqual(q.unfinished(), 1) + def test_simple_queue(self): # Do it a couple of times on the same queue. # Done twice to make sure works with same instance reused.