Skip to content

Commit 0aa0f8d

Browse files
committed
gh-126743: Wake pending async results when a pool terminates
1 parent 114f465 commit 0aa0f8d

4 files changed

Lines changed: 158 additions & 13 deletions

File tree

‎Doc/library/multiprocessing.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2635,6 +2635,11 @@ with the :class:`Pool` class.
26352635
:exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
26362636
an exception then that exception will be reraised by :meth:`get`.
26372637

2638+
.. versionchanged:: 3.16
2639+
If the call is abandoned when the pool is terminated, the result
2640+
becomes ready and :meth:`get` raises :exc:`RuntimeError`.
2641+
Neither callback is invoked for this result.
2642+
26382643
.. method:: wait([timeout])
26392644

26402645
Wait until the result is available or until *timeout* seconds pass.

‎Lib/multiprocessing/pool.py‎

Lines changed: 69 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -156,8 +156,35 @@ class _PoolCache(dict):
156156
"""
157157
def __init__(self, /, *args, notifier=None, **kwds):
158158
self.notifier = notifier
159+
self._async_registration_lock = threading.Lock()
160+
self._accept_async_results = True
159161
super().__init__(*args, **kwds)
160162

163+
def register_async_result(self, result):
164+
with self._async_registration_lock:
165+
if not self._accept_async_results:
166+
raise ValueError("Pool not running")
167+
self[result._job] = result
168+
169+
def stop_async_submissions(self):
170+
with self._async_registration_lock:
171+
self._accept_async_results = False
172+
173+
def cancel_async_results(self, *, except_job=None):
174+
for job, result in self.copy().items():
175+
if job != except_job and isinstance(result, ApplyResult):
176+
# The worker handler was already notified to stop.
177+
self.pop(job)
178+
result._cancel()
179+
180+
def publish(self, job, index, value):
181+
thread = threading.current_thread()
182+
thread._publishing_pool_job = job
183+
try:
184+
self[job]._set(index, value)
185+
finally:
186+
del thread._publishing_pool_job
187+
161188
def __delitem__(self, item):
162189
super().__delitem__(item)
163190

@@ -241,17 +268,18 @@ def __init__(self, processes=None, initializer=None, initargs=(),
241268

242269

243270
self._task_handler = threading.Thread(
244-
target=Pool._handle_tasks,
245-
args=(self._taskqueue, self._quick_put, self._outqueue,
246-
self._pool, self._cache)
271+
target=Pool._run_handler,
272+
args=(self._cache, Pool._handle_tasks, self._taskqueue,
273+
self._quick_put, self._outqueue, self._pool)
247274
)
248275
self._task_handler.daemon = True
249276
self._task_handler._state = RUN
250277
self._task_handler.start()
251278

252279
self._result_handler = threading.Thread(
253-
target=Pool._handle_results,
254-
args=(self._outqueue, self._quick_get, self._cache)
280+
target=Pool._run_handler,
281+
args=(self._cache, Pool._handle_results, self._outqueue,
282+
self._quick_get)
255283
)
256284
self._result_handler.daemon = True
257285
self._result_handler._state = RUN
@@ -438,6 +466,7 @@ def apply_async(self, func, args=(), kwds={}, callback=None,
438466
'''
439467
self._check_running()
440468
result = ApplyResult(self, callback, error_callback)
469+
self._cache.register_async_result(result)
441470
self._taskqueue.put(([(result._job, 0, func, args, kwds)], None))
442471
return result
443472

@@ -468,6 +497,8 @@ def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
468497
task_batches = Pool._get_tasks(func, iterable, chunksize)
469498
result = MapResult(self, chunksize, len(iterable), callback,
470499
error_callback=error_callback)
500+
if result._number_left:
501+
self._cache.register_async_result(result)
471502
self._taskqueue.put(
472503
(
473504
self._guarded_task_generation(result._job,
@@ -540,6 +571,15 @@ def _handle_workers(cls, cache, taskqueue, ctx, Process, processes,
540571
taskqueue.put(None)
541572
util.debug('worker handler exiting')
542573

574+
@staticmethod
575+
def _run_handler(cache, target, *args):
576+
try:
577+
target(*args, cache)
578+
finally:
579+
thread = threading.current_thread()
580+
if getattr(thread, '_cancel_pending_results', False):
581+
cache.cancel_async_results()
582+
543583
@staticmethod
544584
def _handle_tasks(taskqueue, put, outqueue, pool, cache):
545585
thread = threading.current_thread()
@@ -557,7 +597,7 @@ def _handle_tasks(taskqueue, put, outqueue, pool, cache):
557597
except Exception as e:
558598
job, idx = task[:2]
559599
try:
560-
cache[job]._set(idx, (False, e))
600+
cache.publish(job, idx, (False, e))
561601
except KeyError:
562602
pass
563603
else:
@@ -608,7 +648,7 @@ def _handle_results(outqueue, get, cache):
608648

609649
job, i, obj = task
610650
try:
611-
cache[job]._set(i, obj)
651+
cache.publish(job, i, obj)
612652
except KeyError:
613653
pass
614654
task = job = obj = None
@@ -625,7 +665,7 @@ def _handle_results(outqueue, get, cache):
625665
continue
626666
job, i, obj = task
627667
try:
628-
cache[job]._set(i, obj)
668+
cache.publish(job, i, obj)
629669
except KeyError:
630670
pass
631671
task = job = obj = None
@@ -703,6 +743,7 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
703743
taskqueue_buffersize_semaphores):
704744
# this is guaranteed to only be called once
705745
util.debug('finalizing pool')
746+
cache.stop_async_submissions()
706747

707748
# Notify that the worker_handler state has been changed so the
708749
# _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,
730771
# We must wait for the worker handler to exit before terminating
731772
# workers because we don't want workers to be restarted behind our back.
732773
util.debug('joining worker handler')
733-
if threading.current_thread() is not worker_handler:
774+
current_thread = threading.current_thread()
775+
if current_thread is not worker_handler:
734776
worker_handler.join()
735777

736778
# Terminate workers which haven't already finished.
@@ -741,13 +783,23 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
741783
p.terminate()
742784

743785
util.debug('joining task handler')
744-
if threading.current_thread() is not task_handler:
786+
if current_thread is not task_handler:
745787
task_handler.join()
746788

747789
util.debug('joining result handler')
748-
if threading.current_thread() is not result_handler:
790+
if current_thread is not result_handler:
749791
result_handler.join()
750792

793+
# A callback may be publishing a result on the terminating thread.
794+
# Leave that result alone until its handler exits, but wake waiters
795+
# on other results now, including the callback itself.
796+
publishing_job = None
797+
if current_thread in (task_handler, result_handler):
798+
publishing_job = getattr(current_thread, '_publishing_pool_job',
799+
None)
800+
current_thread._cancel_pending_results = publishing_job is not None
801+
cache.cancel_async_results(except_job=publishing_job)
802+
751803
if pool and hasattr(pool[0], 'terminate'):
752804
util.debug('joining pool workers')
753805
for p in pool:
@@ -786,7 +838,6 @@ def __init__(self, pool, callback, error_callback):
786838
self._cache = pool._cache
787839
self._callback = callback
788840
self._error_callback = error_callback
789-
self._cache[self._job] = self
790841

791842
def ready(self):
792843
return self._event.is_set()
@@ -808,6 +859,12 @@ def get(self, timeout=None):
808859
else:
809860
raise self._value
810861

862+
def _cancel(self):
863+
self._success = False
864+
self._value = RuntimeError("Pool has been terminated")
865+
self._pool = None
866+
self._event.set()
867+
811868
def _set(self, i, obj):
812869
self._success, self._value = obj
813870
try:
@@ -849,7 +906,6 @@ def __init__(self, pool, chunksize, length, callback, error_callback):
849906
if chunksize <= 0:
850907
self._number_left = 0
851908
self._event.set()
852-
del self._cache[self._job]
853909
else:
854910
self._number_left = length//chunksize + bool(length % chunksize)
855911

‎Lib/test/_test_multiprocessing.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3516,6 +3516,87 @@ def raise_with_context(exc):
35163516
def unpickleable_result():
35173517
return lambda: 42
35183518

3519+
class _TestPoolTermination(BaseTestCase):
3520+
ALLOWED_TYPES = ('processes',)
3521+
3522+
@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
3523+
def test_terminate_async_results(self):
3524+
callbacks = []
3525+
with self.Pool(1) as pool:
3526+
completed = pool.apply_async(sqr, (2,))
3527+
self.assertEqual(completed.get(support.SHORT_TIMEOUT), 4)
3528+
3529+
pending = pool.apply_async(
3530+
time.sleep, (support.LONG_TIMEOUT,),
3531+
callback=callbacks.append, error_callback=callbacks.append,
3532+
)
3533+
mapped = pool.map_async(
3534+
time.sleep, [support.LONG_TIMEOUT] * 2, chunksize=1,
3535+
callback=callbacks.append, error_callback=callbacks.append,
3536+
)
3537+
waiter_started = threading.Event()
3538+
waiter_outcome = pyqueue.SimpleQueue()
3539+
wait = pending.wait
3540+
3541+
def signal_and_wait(timeout):
3542+
waiter_started.set()
3543+
wait(timeout)
3544+
3545+
def get_pending():
3546+
try:
3547+
waiter_outcome.put(pending.get(support.SHORT_TIMEOUT))
3548+
except Exception as exc:
3549+
waiter_outcome.put(exc)
3550+
3551+
waiter = threading.Thread(target=get_pending)
3552+
with unittest.mock.patch.object(pending, 'wait', signal_and_wait):
3553+
with threading_helper.start_threads([waiter]):
3554+
self.assertTrue(waiter_started.wait(support.SHORT_TIMEOUT))
3555+
pool.terminate()
3556+
3557+
self.assertIsInstance(waiter_outcome.get_nowait(), RuntimeError)
3558+
for result in (pending, mapped):
3559+
with self.subTest(result=type(result)):
3560+
self.assertTrue(result.ready())
3561+
self.assertFalse(result.successful())
3562+
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
3563+
result.get(0)
3564+
self.assertEqual(completed.get(0), 4)
3565+
self.assertTrue(completed.successful())
3566+
self.assertEqual(callbacks, [])
3567+
3568+
@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
3569+
def test_terminate_from_result_callback(self):
3570+
submitted = threading.Event()
3571+
with self.Pool(1) as pool:
3572+
def terminate(_):
3573+
if not submitted.wait(support.SHORT_TIMEOUT):
3574+
raise AssertionError('The second job was not submitted')
3575+
pool.terminate()
3576+
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
3577+
pending.get(0.25)
3578+
3579+
completed = pool.apply_async(sqr, (2,), callback=terminate)
3580+
try:
3581+
pending = pool.apply_async(time.sleep, (support.LONG_TIMEOUT,))
3582+
finally:
3583+
submitted.set()
3584+
self.assertEqual(completed.get(support.SHORT_TIMEOUT), 4)
3585+
pool.join()
3586+
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
3587+
pending.get(0)
3588+
3589+
@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
3590+
def test_terminate_during_map_submission(self):
3591+
with self.Pool(1) as pool:
3592+
def inputs():
3593+
pool.terminate()
3594+
yield 2
3595+
3596+
with self.assertRaisesRegex(ValueError, 'Pool not running'):
3597+
pool.map_async(sqr, inputs())
3598+
3599+
35193600
class _TestPoolCallbackErrors(BaseTestCase):
35203601
ALLOWED_TYPES = ('processes', )
35213602

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Wake callers waiting for pending asynchronous results when a
2+
:class:`multiprocessing.Pool` is terminated. Calling ``get()`` on
3+
an abandoned result now raises :exc:`RuntimeError`.

0 commit comments

Comments
 (0)