Skip to content

Commit 2dc9463

Browse files
pythongh-94440: Fix issue of ProcessPoolExecutor shutdown hanging (python#94468)
Fix an issue of concurrent.futures ProcessPoolExecutor shutdown hanging. Co-authored-by: Alex Waygood <[email protected]>
1 parent a44553e commit 2dc9463

File tree

4 files changed

+36
-0
lines changed

4 files changed

+36
-0
lines changed

Lib/concurrent/futures/process.py

+5
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,11 @@ def run(self):
366366
if self.is_shutting_down():
367367
self.flag_executor_shutting_down()
368368

369+
# When only canceled futures remain in pending_work_items, our
370+
# next call to wait_result_broken_or_wakeup would hang forever.
371+
# This makes sure we have some running futures or none at all.
372+
self.add_call_item_to_queue()
373+
369374
# Since no new work items can be added, it is safe to shutdown
370375
# this thread if there are no pending work items.
371376
if not self.pending_work_items:

Lib/test/test_concurrent_futures.py

+28
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from logging.handlers import QueueHandler
1515
import os
1616
import queue
17+
import signal
1718
import sys
1819
import threading
1920
import time
@@ -397,6 +398,33 @@ def test_hang_gh83386(self):
397398
self.assertFalse(err)
398399
self.assertEqual(out.strip(), b"apple")
399400

401+
def test_hang_gh94440(self):
402+
"""shutdown(wait=True) doesn't hang when a future was submitted and
403+
quickly canceled right before shutdown.
404+
405+
See https://github.com/python/cpython/issues/94440.
406+
"""
407+
if not hasattr(signal, 'alarm'):
408+
raise unittest.SkipTest(
409+
"Tested platform does not support the alarm signal")
410+
411+
def timeout(_signum, _frame):
412+
raise RuntimeError("timed out waiting for shutdown")
413+
414+
kwargs = {}
415+
if getattr(self, 'ctx', None):
416+
kwargs['mp_context'] = self.get_context()
417+
executor = self.executor_type(max_workers=1, **kwargs)
418+
executor.submit(int).result()
419+
old_handler = signal.signal(signal.SIGALRM, timeout)
420+
try:
421+
signal.alarm(5)
422+
executor.submit(int).cancel()
423+
executor.shutdown(wait=True)
424+
finally:
425+
signal.alarm(0)
426+
signal.signal(signal.SIGALRM, old_handler)
427+
400428

401429
class ThreadPoolShutdownTest(ThreadPoolMixin, ExecutorShutdownTest, BaseTestCase):
402430
def test_threads_terminate(self):

Misc/ACKS

+1
Original file line numberDiff line numberDiff line change
@@ -1385,6 +1385,7 @@ Thomas Perl
13851385
Mathieu Perreault
13861386
Mark Perrego
13871387
Trevor Perrin
1388+
Yonatan Perry
13881389
Gabriel de Perthuis
13891390
Tim Peters
13901391
Benjamin Peterson
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a :mod:`concurrent.futures.process` bug where ``ProcessPoolExecutor`` shutdown
2+
could hang after a future has been quickly submitted and canceled.

0 commit comments

Comments
 (0)