Skip to content

Multiprocessing.Pool hangs after re-spawning several worker process. #76067

Open

Description

@olarn
mannequin
BPO 31886
Nosy @pitrou, @ogrisel, @applio, @tomMoral

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields:

assignee = None
closed_at = None
created_at = <Date 2017-10-27.15:10:27.152>
labels = ['3.7', 'type-bug', 'library']
title = 'Multiprocessing.Pool hangs after re-spawning several worker process.'
updated_at = <Date 2017-10-29.11:02:09.684>
user = 'https://bugs.python.org/olarn'

bugs.python.org fields:

activity = <Date 2017-10-29.11:02:09.684>
actor = 'pitrou'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = ['Library (Lib)']
creation = <Date 2017-10-27.15:10:27.152>
creator = 'olarn'
dependencies = []
files = []
hgrepos = []
issue_num = 31886
keywords = []
message_count = 2.0
messages = ['305124', '305185']
nosy_count = 5.0
nosy_names = ['pitrou', 'Olivier.Grisel', 'davin', 'tomMoral', 'olarn']
pr_nums = []
priority = 'normal'
resolution = None
stage = None
status = 'open'
superseder = None
type = 'behavior'
url = 'https://bugs.python.org/issue31886'
versions = ['Python 2.7', 'Python 3.6', 'Python 3.7']

Linked PRs

Activity

  1. olarn commented on Oct 27, 2017

    olarnmannequin
    MannequinAuthor

    Multiprocessing's pool apparently attempts to repopulate the pool in an event of sub-process worker crash. However the pool seems to hangs after about ~ 4*(number of worker) process re-spawns.

    I've tracked the issue down to queue.get() stalling at multiprocessing.pool, line 102

    Is this a known issue? Are there any known workaround?

    To reproduce this issue:

    import multiprocessing
    import multiprocessing.util
    import logging
    
    multiprocessing.util._logger = multiprocessing.util.log_to_stderr(logging.DEBUG)
    import time
    import ctypes
    
    
    def crash_py_interpreter():
        print("attempting to crash the interpreter in ", multiprocessing.current_process())
        i = ctypes.c_char('a'.encode())
        j = ctypes.pointer(i)
        c = 0
        while True:
            j[c] = 'a'.encode()
            c += 1
        j
    
    
    def test_fn(x):
        print("test_fn in ", multiprocessing.current_process().name, x)
        exit(0)
    
        time.sleep(0.1)
    
    
    if __name__ == '__main__':
    
        # pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
        pool = multiprocessing.Pool(processes=1)
    
        args_queue = [n for n in range(20)]
    
        # subprocess quits
        pool.map(test_fn, args_queue)
    # subprocess crashes
    # pool.map(test_fn,queue)
    
  2. added
    stdlib
    type-bug
    on Oct 27, 2017
  3. pitrou commented on Oct 29, 2017

    @pitrou
    Member

    Generally speaking, queues can remain in an inconsistent state after a process crash (because the process might have crashed just after acquiring a shared semaphore or sending part of a large message). It's not obvious to me how we could make them safer, at least under Unix where there's no widely-available message-oriented communication facility that I know of.

  4. transferred this issue fromon Apr 10, 2022
  5. dxdc commented on Oct 21, 2026

    @dxdc

    I hit this through the multiprocess fork of this module (uqfoundation/multiprocess#220), and I believe I've tracked down the cause, at least for the exit() case in the original report. It isn't related to how many workers have been respawned, and the queues aren't left in a bad state. The worker loop in Lib/multiprocessing/pool.py only catches Exception around the task:

    try:
        result = (True, func(*args, **kwds))
    except Exception as e:
        ...

    So a SystemExit (from exit(), sys.exit(), or a SIGTERM handler that raises it) escapes the loop, and the worker process exits before it ever sends a result back. The pool replaces the worker, but that job's result never arrives, so map() / get() waits forever.

    The "about 4x the number of workers" in the original report is just how map() chunks the work. With Pool(1) and 20 items it sends 4 chunks of 5, each chunk takes out its worker, so you see 4 respawns and then the hang. It still reproduces on main (3.16.0a1) and on 3.11-3.13, with fork, spawn and forkserver:

    import multiprocessing
    
    def task(x):
        raise SystemExit(0)
    
    if __name__ == "__main__":
        with multiprocessing.Pool(1) as pool:
            pool.map(task, range(20))  # hangs forever

    The way I hit it in practice was a worker that installs a SIGTERM handler raising SystemExit for graceful shutdown.

    I have a fix: catch BaseException in the worker and send it back like any other exception, so get() raises it, the same way Future.result() does for ProcessPoolExecutor. Unlike ProcessPoolExecutor, the worker process then re-raises it once the result has been sent, so it still exits with the same exit code and the pool replaces it. I went that way rather than keeping the worker alive because a worker that swallows SystemExit hangs in a different way: if it's busy when pool.terminate() sends SIGTERM and its handler raises SystemExit, it goes back for more work and blocks on the queue lock that terminate() is holding. ThreadPool threads report the exception and keep running, since ThreadPool only replaces an exited thread when its worker handler happens to wake up, so jobs queued behind it would still hang.

    This only covers tasks that raise. A worker that dies outright (os._exit(), a segfault like the commented-out ctypes case, SIGKILL or the OOM killer) still hangs the pool. That's the broader gh-66587, and Antoine's point about queue state applies there, so I'll leave it to you whether this issue should be closed by the fix. PR posted as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.7 (EOL)stdlibtopic-multiprocessingtype-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions