Skip to content

Commit 4ff14d8

Browse files
committed
gh-126743: Wake abandoned results before joining pool handlers
1 parent 0aa0f8d commit 4ff14d8

2 files changed

Lines changed: 110 additions & 40 deletions

File tree

‎Lib/multiprocessing/pool.py‎

Lines changed: 43 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -156,34 +156,53 @@ class _PoolCache(dict):
156156
"""
157157
def __init__(self, /, *args, notifier=None, **kwds):
158158
self.notifier = notifier
159-
self._async_registration_lock = threading.Lock()
159+
self._async_lock = threading.Lock()
160160
self._accept_async_results = True
161+
self._publishing = {}
161162
super().__init__(*args, **kwds)
162163

163164
def register_async_result(self, result):
164-
with self._async_registration_lock:
165+
with self._async_lock:
165166
if not self._accept_async_results:
166167
raise ValueError("Pool not running")
167168
self[result._job] = result
168169

169-
def stop_async_submissions(self):
170-
with self._async_registration_lock:
170+
def cancel_async_results(self):
171+
with self._async_lock:
171172
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.
173+
abandoned = [
177174
self.pop(job)
178-
result._cancel()
175+
for job, result in self.copy().items()
176+
if isinstance(result, ApplyResult) and job not in self._publishing
177+
]
178+
for result in abandoned:
179+
result._cancel()
179180

180181
def publish(self, job, index, value):
181-
thread = threading.current_thread()
182-
thread._publishing_pool_job = job
182+
with self._async_lock:
183+
result = self[job]
184+
is_async = isinstance(result, ApplyResult)
185+
if is_async:
186+
if not self._accept_async_results:
187+
return
188+
self._publishing[job] = self._publishing.get(job, 0) + 1
183189
try:
184-
self[job]._set(index, value)
190+
result._set(index, value)
185191
finally:
186-
del thread._publishing_pool_job
192+
if is_async:
193+
self._finish_publication(job)
194+
195+
def _finish_publication(self, job):
196+
abandoned = None
197+
with self._async_lock:
198+
self._publishing[job] -= 1
199+
if self._publishing[job] == 0:
200+
del self._publishing[job]
201+
if not self._accept_async_results:
202+
# An interrupted map may still have outstanding chunks.
203+
abandoned = self.pop(job, None)
204+
if abandoned is not None:
205+
abandoned._cancel()
187206

188207
def __delitem__(self, item):
189208
super().__delitem__(item)
@@ -268,18 +287,17 @@ def __init__(self, processes=None, initializer=None, initargs=(),
268287

269288

270289
self._task_handler = threading.Thread(
271-
target=Pool._run_handler,
272-
args=(self._cache, Pool._handle_tasks, self._taskqueue,
273-
self._quick_put, self._outqueue, self._pool)
290+
target=Pool._handle_tasks,
291+
args=(self._taskqueue, self._quick_put, self._outqueue,
292+
self._pool, self._cache)
274293
)
275294
self._task_handler.daemon = True
276295
self._task_handler._state = RUN
277296
self._task_handler.start()
278297

279298
self._result_handler = threading.Thread(
280-
target=Pool._run_handler,
281-
args=(self._cache, Pool._handle_results, self._outqueue,
282-
self._quick_get)
299+
target=Pool._handle_results,
300+
args=(self._outqueue, self._quick_get, self._cache)
283301
)
284302
self._result_handler.daemon = True
285303
self._result_handler._state = RUN
@@ -571,15 +589,6 @@ def _handle_workers(cls, cache, taskqueue, ctx, Process, processes,
571589
taskqueue.put(None)
572590
util.debug('worker handler exiting')
573591

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-
583592
@staticmethod
584593
def _handle_tasks(taskqueue, put, outqueue, pool, cache):
585594
thread = threading.current_thread()
@@ -743,7 +752,6 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
743752
taskqueue_buffersize_semaphores):
744753
# this is guaranteed to only be called once
745754
util.debug('finalizing pool')
746-
cache.stop_async_submissions()
747755

748756
# Notify that the worker_handler state has been changed so the
749757
# _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,
752760
change_notifier.put(None)
753761

754762
task_handler._state = TERMINATE
763+
764+
# A callback may be waiting for another result. Settle abandoned
765+
# results before waiting for any handler to finish.
766+
cache.cancel_async_results()
767+
755768
# Release all semaphores to wake up task_handler to stop.
756769
for buffersize_sema in tuple(taskqueue_buffersize_semaphores):
757770
buffersize_sema.release()
@@ -790,16 +803,6 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
790803
if current_thread is not result_handler:
791804
result_handler.join()
792805

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-
803806
if pool and hasattr(pool[0], 'terminate'):
804807
util.debug('joining pool workers')
805808
for p in pool:

‎Lib/test/_test_multiprocessing.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3586,6 +3586,73 @@ def terminate(_):
35863586
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
35873587
pending.get(0)
35883588

3589+
@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
3590+
def test_terminate_while_result_callback_waits(self):
3591+
started = threading.Event()
3592+
joining = threading.Event()
3593+
3594+
with self.Pool(1) as pool:
3595+
result_handler_join = pool._result_handler.join
3596+
3597+
def join_result_handler():
3598+
joining.set()
3599+
result_handler_join()
3600+
3601+
def callback(_):
3602+
started.set()
3603+
self.assertTrue(joining.wait(support.SHORT_TIMEOUT))
3604+
pool.terminate()
3605+
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
3606+
pending.get(0.5)
3607+
3608+
completed = pool.apply_async(sqr, (2,), callback=callback)
3609+
pending = pool.apply_async(time.sleep, (support.LONG_TIMEOUT,))
3610+
self.assertTrue(started.wait(support.SHORT_TIMEOUT))
3611+
with unittest.mock.patch.object(
3612+
pool._result_handler, 'join', join_result_handler
3613+
):
3614+
pool.terminate()
3615+
3616+
self.assertEqual(completed.get(0), 4)
3617+
self.assertTrue(pending.ready())
3618+
3619+
@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
3620+
def test_terminate_during_map_result_publication(self):
3621+
from multiprocessing.pool import MapResult
3622+
3623+
publishing = threading.Event()
3624+
joining = threading.Event()
3625+
set_result = MapResult._set
3626+
3627+
def publish_chunk(result, index, value):
3628+
publishing.set()
3629+
if not joining.wait(support.SHORT_TIMEOUT):
3630+
raise AssertionError('The terminator did not reach the join')
3631+
set_result(result, index, value)
3632+
3633+
with self.Pool(1) as pool:
3634+
result_handler_join = pool._result_handler.join
3635+
3636+
def join_result_handler():
3637+
try:
3638+
self.assertFalse(mapped.ready())
3639+
finally:
3640+
joining.set()
3641+
result_handler_join()
3642+
3643+
with unittest.mock.patch.object(MapResult, '_set', publish_chunk):
3644+
mapped = pool.map_async(
3645+
time.sleep, [0, support.LONG_TIMEOUT], chunksize=1,
3646+
)
3647+
self.assertTrue(publishing.wait(support.SHORT_TIMEOUT))
3648+
with unittest.mock.patch.object(
3649+
pool._result_handler, 'join', join_result_handler
3650+
):
3651+
pool.terminate()
3652+
3653+
with self.assertRaisesRegex(RuntimeError, 'Pool has been terminated'):
3654+
mapped.get(0)
3655+
35893656
@warnings_helper.ignore_fork_in_thread_deprecation_warnings()
35903657
def test_terminate_during_map_submission(self):
35913658
with self.Pool(1) as pool:

0 commit comments

Comments
 (0)