From 0aa0f8ddad8d1ca5dd58ca848593d1bd64fbb7f8 Mon Sep 17 00:00:00 2001 From: qlearzyy Date: Mon, 30 Nov 2026 21:15:26 +0100 Subject: [PATCH 1/3] gh-126743: Wake pending async results when a pool terminates --- Doc/library/multiprocessing.rst | 5 ++ Lib/multiprocessing/pool.py | 82 ++++++++++++++++--- Lib/test/_test_multiprocessing.py | 81 ++++++++++++++++++ ...-11-30-21-11-20.gh-issue-126743.xj4JpV.rst | 3 + 4 files changed, 158 insertions(+), 13 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index dc45f8401541f45..958d69c3d75a4f0 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -2635,6 +2635,11 @@ with the :class:`Pool` class. :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised an exception then that exception will be reraised by :meth:`get`. + .. versionchanged:: 3.16 + If the call is abandoned when the pool is terminated, the result + becomes ready and :meth:`get` raises :exc:`RuntimeError`. + Neither callback is invoked for this result. + .. method:: wait([timeout]) Wait until the result is available or until *timeout* seconds pass. diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py index ef9460ac0aa6817..906e1351032e6de 100644 --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -156,8 +156,35 @@ class _PoolCache(dict): """ def __init__(self, /, *args, notifier=None, **kwds): self.notifier = notifier + self._async_registration_lock = threading.Lock() + self._accept_async_results = True super().__init__(*args, **kwds) + def register_async_result(self, result): + with self._async_registration_lock: + if not self._accept_async_results: + raise ValueError("Pool not running") + self[result._job] = result + + def stop_async_submissions(self): + with self._async_registration_lock: + self._accept_async_results = False + + def cancel_async_results(self, *, except_job=None): + for job, result in self.copy().items(): + if job != except_job and isinstance(result, ApplyResult): + # The worker handler was already notified to stop. + self.pop(job) + result._cancel() + + def publish(self, job, index, value): + thread = threading.current_thread() + thread._publishing_pool_job = job + try: + self[job]._set(index, value) + finally: + del thread._publishing_pool_job + def __delitem__(self, item): super().__delitem__(item) @@ -241,17 +268,18 @@ def __init__(self, processes=None, initializer=None, initargs=(), self._task_handler = threading.Thread( - target=Pool._handle_tasks, - args=(self._taskqueue, self._quick_put, self._outqueue, - self._pool, self._cache) + target=Pool._run_handler, + args=(self._cache, Pool._handle_tasks, self._taskqueue, + self._quick_put, self._outqueue, self._pool) ) self._task_handler.daemon = True self._task_handler._state = RUN self._task_handler.start() self._result_handler = threading.Thread( - target=Pool._handle_results, - args=(self._outqueue, self._quick_get, self._cache) + target=Pool._run_handler, + args=(self._cache, Pool._handle_results, self._outqueue, + self._quick_get) ) self._result_handler.daemon = True self._result_handler._state = RUN @@ -438,6 +466,7 @@ def apply_async(self, func, args=(), kwds={}, callback=None, ''' self._check_running() result = ApplyResult(self, callback, error_callback) + self._cache.register_async_result(result) self._taskqueue.put(([(result._job, 0, func, args, kwds)], None)) return result @@ -468,6 +497,8 @@ def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self, chunksize, len(iterable), callback, error_callback=error_callback) + if result._number_left: + self._cache.register_async_result(result) self._taskqueue.put( ( self._guarded_task_generation(result._job, @@ -540,6 +571,15 @@ def _handle_workers(cls, cache, taskqueue, ctx, Process, processes, taskqueue.put(None) util.debug('worker handler exiting') + @staticmethod + def _run_handler(cache, target, *args): + try: + target(*args, cache) + finally: + thread = threading.current_thread() + if getattr(thread, '_cancel_pending_results', False): + cache.cancel_async_results() + @staticmethod def _handle_tasks(taskqueue, put, outqueue, pool, cache): thread = threading.current_thread() @@ -557,7 +597,7 @@ def _handle_tasks(taskqueue, put, outqueue, pool, cache): except Exception as e: job, idx = task[:2] try: - cache[job]._set(idx, (False, e)) + cache.publish(job, idx, (False, e)) except KeyError: pass else: @@ -608,7 +648,7 @@ def _handle_results(outqueue, get, cache): job, i, obj = task try: - cache[job]._set(i, obj) + cache.publish(job, i, obj) except KeyError: pass task = job = obj = None @@ -625,7 +665,7 @@ def _handle_results(outqueue, get, cache): continue job, i, obj = task try: - cache[job]._set(i, obj) + cache.publish(job, i, obj) except KeyError: pass task = job = obj = None @@ -703,6 +743,7 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, taskqueue_buffersize_semaphores): # this is guaranteed to only be called once util.debug('finalizing pool') + cache.stop_async_submissions() # Notify that the worker_handler state has been changed so the # _handle_workers loop can be unblocked (and exited) in order to @@ -730,7 +771,8 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, # We must wait for the worker handler to exit before terminating # workers because we don't want workers to be restarted behind our back. util.debug('joining worker handler') - if threading.current_thread() is not worker_handler: + current_thread = threading.current_thread() + if current_thread is not worker_handler: worker_handler.join() # Terminate workers which haven't already finished. @@ -741,13 +783,23 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, p.terminate() util.debug('joining task handler') - if threading.current_thread() is not task_handler: + if current_thread is not task_handler: task_handler.join() util.debug('joining result handler') - if threading.current_thread() is not result_handler: + if current_thread is not result_handler: result_handler.join() + # A callback may be publishing a result on the terminating thread. + # Leave that result alone until its handler exits, but wake waiters + # on other results now, including the callback itself. + publishing_job = None + if current_thread in (task_handler, result_handler): + publishing_job = getattr(current_thread, '_publishing_pool_job', + None) + current_thread._cancel_pending_results = publishing_job is not None + cache.cancel_async_results(except_job=publishing_job) + if pool and hasattr(pool[0], 'terminate'): util.debug('joining pool workers') for p in pool: @@ -786,7 +838,6 @@ def __init__(self, pool, callback, error_callback): self._cache = pool._cache self._callback = callback self._error_callback = error_callback - self._cache[self._job] = self def ready(self): return self._event.is_set() @@ -808,6 +859,12 @@ def get(self, timeout=None): else: raise self._value + def _cancel(self): + self._success = False + self._value = RuntimeError("Pool has been terminated") + self._pool = None + self._event.set() + def _set(self, i, obj): self._success, self._value = obj try: @@ -849,7 +906,6 @@ def __init__(self, pool, chunksize, length, callback, error_callback): if chunksize <= 0: self._number_left = 0 self._event.set() - del self._cache[self._job] else: self._number_left = length//chunksize + bool(length % chunksize) diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 540189147cb4d7b..6230f57829b93ee 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -3516,6 +3516,87 @@ def raise_with_context(exc): def unpickleable_result(): return lambda: 42 +class _TestPoolTermination(BaseTestCase): + ALLOWED_TYPES = ('processes',) + + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_terminate_async_results(self): + callbacks = [] + with self.Pool(1) as pool: + completed = pool.apply_async(sqr, (2,)) + self.assertEqual(completed.get(support.SHORT_TIMEOUT), 4) + + pending = pool.apply_async( + time.sleep, (support.LONG_TIMEOUT,), + callback=callbacks.append, error_callback=callbacks.append, + ) + mapped = pool.map_async( + time.sleep, [support.LONG_TIMEOUT] * 2, chunksize=1, + callback=callbacks.append, error_callback=callbacks.append, + ) + waiter_started = threading.Event() + waiter_outcome = pyqueue.SimpleQueue() + wait = pending.wait + + def signal_and_wait(timeout): + waiter_started.set() + wait(timeout) + + def get_pending(): + try: + waiter_outcome.put(pending.get(support.SHORT_TIMEOUT)) + except Exception as exc: + waiter_outcome.put(exc) + + waiter = threading.Thread(target=get_pending) + with unittest.mock.patch.object(pending, 'wait', signal_and_wait): + with threading_helper.start_threads([waiter]): + self.assertTrue(waiter_started.wait(support.SHORT_TIMEOUT)) + pool.terminate() + + self.assertIsInstance(waiter_outcome.get_nowait(), RuntimeError) + for result in (pending, mapped): + with self.subTest(result=type(result)): + self.assertTrue(result.ready()) + self.assertFalse(result.successful()) + with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'): + result.get(0) + self.assertEqual(completed.get(0), 4) + self.assertTrue(completed.successful()) + self.assertEqual(callbacks, []) + + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_terminate_from_result_callback(self): + submitted = threading.Event() + with self.Pool(1) as pool: + def terminate(_): + if not submitted.wait(support.SHORT_TIMEOUT): + raise AssertionError('The second job was not submitted') + pool.terminate() + with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'): + pending.get(0.25) + + completed = pool.apply_async(sqr, (2,), callback=terminate) + try: + pending = pool.apply_async(time.sleep, (support.LONG_TIMEOUT,)) + finally: + submitted.set() + self.assertEqual(completed.get(support.SHORT_TIMEOUT), 4) + pool.join() + with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'): + pending.get(0) + + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_terminate_during_map_submission(self): + with self.Pool(1) as pool: + def inputs(): + pool.terminate() + yield 2 + + with self.assertRaisesRegex(ValueError, 'Pool not running'): + pool.map_async(sqr, inputs()) + + class _TestPoolCallbackErrors(BaseTestCase): ALLOWED_TYPES = ('processes', ) diff --git a/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst b/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst new file mode 100644 index 000000000000000..9e8b25f1665535c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst @@ -0,0 +1,3 @@ +Wake callers waiting for pending asynchronous results when a +:class:`multiprocessing.Pool` is terminated. Calling ``get()`` on +an abandoned result now raises :exc:`RuntimeError`. From 4ff14d85a8db18192da711d7a11679acff7d9659 Mon Sep 17 00:00:00 2001 From: qlearzyy Date: Mon, 30 Nov 2026 22:41:45 +0100 Subject: [PATCH 2/3] gh-126743: Wake abandoned results before joining pool handlers --- Lib/multiprocessing/pool.py | 83 ++++++++++++++++--------------- Lib/test/_test_multiprocessing.py | 67 +++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 40 deletions(-) diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py index 906e1351032e6de..6693328a478ea6e 100644 --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -156,34 +156,53 @@ class _PoolCache(dict): """ def __init__(self, /, *args, notifier=None, **kwds): self.notifier = notifier - self._async_registration_lock = threading.Lock() + self._async_lock = threading.Lock() self._accept_async_results = True + self._publishing = {} super().__init__(*args, **kwds) def register_async_result(self, result): - with self._async_registration_lock: + with self._async_lock: if not self._accept_async_results: raise ValueError("Pool not running") self[result._job] = result - def stop_async_submissions(self): - with self._async_registration_lock: + def cancel_async_results(self): + with self._async_lock: self._accept_async_results = False - - def cancel_async_results(self, *, except_job=None): - for job, result in self.copy().items(): - if job != except_job and isinstance(result, ApplyResult): - # The worker handler was already notified to stop. + abandoned = [ self.pop(job) - result._cancel() + for job, result in self.copy().items() + if isinstance(result, ApplyResult) and job not in self._publishing + ] + for result in abandoned: + result._cancel() def publish(self, job, index, value): - thread = threading.current_thread() - thread._publishing_pool_job = job + with self._async_lock: + result = self[job] + is_async = isinstance(result, ApplyResult) + if is_async: + if not self._accept_async_results: + return + self._publishing[job] = self._publishing.get(job, 0) + 1 try: - self[job]._set(index, value) + result._set(index, value) finally: - del thread._publishing_pool_job + if is_async: + self._finish_publication(job) + + def _finish_publication(self, job): + abandoned = None + with self._async_lock: + self._publishing[job] -= 1 + if self._publishing[job] == 0: + del self._publishing[job] + if not self._accept_async_results: + # An interrupted map may still have outstanding chunks. + abandoned = self.pop(job, None) + if abandoned is not None: + abandoned._cancel() def __delitem__(self, item): super().__delitem__(item) @@ -268,18 +287,17 @@ def __init__(self, processes=None, initializer=None, initargs=(), self._task_handler = threading.Thread( - target=Pool._run_handler, - args=(self._cache, Pool._handle_tasks, self._taskqueue, - self._quick_put, self._outqueue, self._pool) + target=Pool._handle_tasks, + args=(self._taskqueue, self._quick_put, self._outqueue, + self._pool, self._cache) ) self._task_handler.daemon = True self._task_handler._state = RUN self._task_handler.start() self._result_handler = threading.Thread( - target=Pool._run_handler, - args=(self._cache, Pool._handle_results, self._outqueue, - self._quick_get) + target=Pool._handle_results, + args=(self._outqueue, self._quick_get, self._cache) ) self._result_handler.daemon = True self._result_handler._state = RUN @@ -571,15 +589,6 @@ def _handle_workers(cls, cache, taskqueue, ctx, Process, processes, taskqueue.put(None) util.debug('worker handler exiting') - @staticmethod - def _run_handler(cache, target, *args): - try: - target(*args, cache) - finally: - thread = threading.current_thread() - if getattr(thread, '_cancel_pending_results', False): - cache.cancel_async_results() - @staticmethod def _handle_tasks(taskqueue, put, outqueue, pool, cache): thread = threading.current_thread() @@ -743,7 +752,6 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, taskqueue_buffersize_semaphores): # this is guaranteed to only be called once util.debug('finalizing pool') - cache.stop_async_submissions() # Notify that the worker_handler state has been changed so the # _handle_workers loop can be unblocked (and exited) in order to @@ -752,6 +760,11 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, change_notifier.put(None) task_handler._state = TERMINATE + + # A callback may be waiting for another result. Settle abandoned + # results before waiting for any handler to finish. + cache.cancel_async_results() + # Release all semaphores to wake up task_handler to stop. for buffersize_sema in tuple(taskqueue_buffersize_semaphores): buffersize_sema.release() @@ -790,16 +803,6 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, if current_thread is not result_handler: result_handler.join() - # A callback may be publishing a result on the terminating thread. - # Leave that result alone until its handler exits, but wake waiters - # on other results now, including the callback itself. - publishing_job = None - if current_thread in (task_handler, result_handler): - publishing_job = getattr(current_thread, '_publishing_pool_job', - None) - current_thread._cancel_pending_results = publishing_job is not None - cache.cancel_async_results(except_job=publishing_job) - if pool and hasattr(pool[0], 'terminate'): util.debug('joining pool workers') for p in pool: diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 6230f57829b93ee..5ccb0a103add80a 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -3586,6 +3586,73 @@ def terminate(_): with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'): pending.get(0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_terminate_while_result_callback_waits(self): + started = threading.Event() + joining = threading.Event() + + with self.Pool(1) as pool: + result_handler_join = pool._result_handler.join + + def join_result_handler(): + joining.set() + result_handler_join() + + def callback(_): + started.set() + self.assertTrue(joining.wait(support.SHORT_TIMEOUT)) + pool.terminate() + with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'): + pending.get(0.5) + + completed = pool.apply_async(sqr, (2,), callback=callback) + pending = pool.apply_async(time.sleep, (support.LONG_TIMEOUT,)) + self.assertTrue(started.wait(support.SHORT_TIMEOUT)) + with unittest.mock.patch.object( + pool._result_handler, 'join', join_result_handler + ): + pool.terminate() + + self.assertEqual(completed.get(0), 4) + self.assertTrue(pending.ready()) + + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_terminate_during_map_result_publication(self): + from multiprocessing.pool import MapResult + + publishing = threading.Event() + joining = threading.Event() + set_result = MapResult._set + + def publish_chunk(result, index, value): + publishing.set() + if not joining.wait(support.SHORT_TIMEOUT): + raise AssertionError('The terminator did not reach the join') + set_result(result, index, value) + + with self.Pool(1) as pool: + result_handler_join = pool._result_handler.join + + def join_result_handler(): + try: + self.assertFalse(mapped.ready()) + finally: + joining.set() + result_handler_join() + + with unittest.mock.patch.object(MapResult, '_set', publish_chunk): + mapped = pool.map_async( + time.sleep, [0, support.LONG_TIMEOUT], chunksize=1, + ) + self.assertTrue(publishing.wait(support.SHORT_TIMEOUT)) + with unittest.mock.patch.object( + pool._result_handler, 'join', join_result_handler + ): + pool.terminate() + + with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'): + mapped.get(0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_terminate_during_map_submission(self): with self.Pool(1) as pool: From 23db95d666a382d9a488cf5f4f8da3d8847d30b8 Mon Sep 17 00:00:00 2001 From: qlearzyy Date: Mon, 30 Nov 2026 23:03:40 +0100 Subject: [PATCH 3/3] gh-126743: Fix the NEWS reference to Pool --- .../next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst b/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst index 9e8b25f1665535c..0106228614fd148 100644 --- a/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst +++ b/Misc/NEWS.d/next/Library/2026-11-30-21-11-20.gh-issue-126743.xj4JpV.rst @@ -1,3 +1,3 @@ Wake callers waiting for pending asynchronous results when a -:class:`multiprocessing.Pool` is terminated. Calling ``get()`` on +:class:`multiprocessing.pool.Pool` is terminated. Calling ``get()`` on an abandoned result now raises :exc:`RuntimeError`.