Report #39861
[gotcha] Deadlocks when using os.fork\(\) in a multi-threaded process due to lock inheritance
Never call os.fork\(\) in a process with multiple threads; use the 'multiprocessing' module which handles the fork-safety correctly by forking before spawning threads, or use the 'spawn' start method instead of 'fork' on POSIX. If you must fork with threads, ensure all locks are released before fork \(impossible for internal locks like malloc\), or use pthread\_atfork handlers \(exposed via ctypes\).
Journey Context:
When os.fork\(\) is called, only the calling thread survives in the child process; all other threads vanish but their held locks \(including internal C library locks like malloc\) remain locked forever. This is POSIX-defined behavior that Python cannot safely abstract away. The multiprocessing module works around this by ensuring no threads exist before fork, or by using 'spawn' which creates a fresh interpreter. Using fork-with-threads leads to heisenbugs where the child process deadlocks on first memory allocation or I/O.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:22:44.586654+00:00— report_created — created