Fork, Threads and Other Interpreters

Contents
A Python program starts a thread, the thread takes a lock, and the main thread calls os.fork().
In the child, the lock is still locked, and the thread that holds it doesn’t exist: fork() copies
the whole address space and exactly one thread, the one that called it. Nothing in the child will ever
release that lock. And if the same program has ever created a subinterpreter and not destroyed it, it
doesn’t get that far: on CPython 3.8.5, and on the 3.9 release candidate, the child hangs inside
fork() itself, on a lock that CPython’s own clean-up code takes twice.
This post is about the ways a CPython process divides itself: fork, threads, multiprocessing’s start
methods, and the newest and least finished of them, several interpreters in one process. Each one
shares something, and the leaks in this post are all about which side of the line a piece of C state
turns out to be on.
This is Part 16 of a series on the CPython runtime. Part 4 measured what reference counting does to a forked child’s memory, Part 6 took apart the GIL, and Part 15 showed that a C extension loaded once stays for the life of the process. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.8.5 (July 2020) and the first release candidate of 3.9 (August), both built from their tags with Ubuntu 20.04’s gcc 9.3, on 3.7.0 from Part 3 for one comparison, and on the stock Pythons of Ubuntu 18.04 and 20.04 for another. The note at the end says exactly where and how.
fork copies one thread
import os, threading, time
lock = threading.Lock()
def worker():
with lock:
time.sleep(2) # holds the lock across the fork
t = threading.Thread(target=worker, name="worker")
t.start()
time.sleep(0.2) # let the worker take the lock
pid = os.fork()
if pid == 0:
print("child: threads", [th.name for th in threading.enumerate()],
"kernel tasks", len(os.listdir("/proc/self/task")), flush=True)
print("child: lock.locked() =", lock.locked(), flush=True)
start = time.monotonic()
got = lock.acquire(timeout=5) # without a timeout, this waits forever
print("child: acquired after %.1f s? %s" % (time.monotonic() - start, got), flush=True)
os._exit(0)
os.waitpid(pid, 0)
t.join()
print("parent: threads", [th.name for th in threading.enumerate()], "lock.locked() =", lock.locked())
$ python3 forklock.py
child: threads ['MainThread'] kernel tasks 1
child: lock.locked() = True
child: acquired after 5.0 s? False
parent: threads ['MainThread'] lock.locked() = False
The child has one kernel task, and threading knows it: enumerate() lists only the main thread. But
the lock is a PyThread_type_lock, in CPython’s case a POSIX semaphore, a few bytes of memory that say
“taken”, and fork copied those bytes. In the parent, the worker released its lock two seconds later.
In the child, nothing ever will. With a plain lock.acquire(), the child would wait forever, and the
program would hang in a way that depends on timing: fork a millisecond earlier or later and the lock is
free.
What CPython does around fork
os.fork() doesn’t just call fork(). In 3.8 it calls PyOS_BeforeFork, which runs any Python
functions registered to run before a fork and then takes the import lock, so that no other thread is
halfway through importing a module when the copy is made. After the fork the parent releases it, and the
child runs PyOS_AfterFork_Child, in Modules/posixmodule.c:
void
PyOS_AfterFork_Child(void)
{
_PyRuntimeState *runtime = &_PyRuntime;
_PyGILState_Reinit(runtime);
_PyEval_ReInitThreads(runtime);
_PyImport_ReInitLock();
_PySignal_AfterFork();
_PyRuntimeState_ReInitThreads(runtime);
_PyInterpreterState_DeleteExceptMain(runtime);
run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
}
It makes a fresh GIL and gives it to the calling thread, throws away the thread states of every other
thread, makes a fresh import lock, resets signal handling, deletes every interpreter but the main one
(remember that line), and runs the registered after-fork functions. CPython repairs its own locks. Yours
are your problem, and since 3.7, os.register_at_fork is the tool for it:
import os, threading, time
lock = threading.Lock()
os.register_at_fork(before=lock.acquire, # wait until no thread holds it
after_in_parent=lock.release,
after_in_child=lock.release)
def worker():
with lock:
time.sleep(2)
threading.Thread(target=worker).start()
time.sleep(0.2)
start = time.monotonic()
pid = os.fork()
if pid == 0:
got = lock.acquire(timeout=5)
print("child: acquired at once? %s" % got, flush=True)
os._exit(0)
print("parent: fork() returned after %.1f s" % (time.monotonic() - start), flush=True)
os.waitpid(pid, 0)
$ python3 forkfix.py
parent: fork() returned after 1.8 s
child: acquired at once? True
The before handler takes the lock itself, which waits until the worker has finished with it, so the
fork happens at a moment when the lock is held by the thread doing the forking. Both sides then release
it. The cost is visible: fork() took 1.8 seconds, the rest of the worker’s sleep. The alternative, a
fresh lock created in the child, is faster and quietly wrong if the lock was protecting data the worker
was halfway through changing.
The standard library’s own locks
logging has a lock in every handler, held while a record is formatted and written, and a program that
logs from threads and forks is common. Here a handler holds its lock for a second when called from a
thread, the program forks during that second, and the child logs:
import logging, os, signal, sys, threading, time
class Slow(logging.StreamHandler):
def emit(self, record):
if threading.current_thread() is not threading.main_thread():
time.sleep(1) # the thread holds the handler's lock for a second
super().emit(record)
logging.basicConfig(level=logging.INFO, handlers=[Slow(sys.stdout)], format="%(process)s %(message)s")
threading.Thread(target=lambda: logging.info("from a thread"), daemon=True).start()
time.sleep(0.2)
pid = os.fork()
if pid == 0:
signal.alarm(3) # a deadlocked child gets killed after 3 s
start = time.monotonic()
logging.info("from the child")
print("child: logging took %.1f s" % (time.monotonic() - start), flush=True)
os._exit(0)
_, status = os.waitpid(pid, 0)
print("Python %s: child %s" % (sys.version.split()[0],
"exited normally" if os.WIFEXITED(status) else "killed by signal %d" % os.WTERMSIG(status)), flush=True)
time.sleep(1)
$ /opt/py/3.7.0/bin/python3 logfork.py
596 from a thread
Python 3.7.0: child killed by signal 14
$ python3 logfork.py
503 from the child
child: logging took 0.0 s
Python 3.8.5: child exited normally
501 from a thread
On 3.7.0 the child blocked on the handler’s lock until the alarm killed it (signal 14 is SIGALRM), and
never printed anything. On 3.8.5 it logged at once. Somewhere in the 3.7 series logging started using
register_at_fork on itself: before a fork it takes its module lock, and in the child it calls
createLock() on every handler it knows of, giving each a fresh lock. That’s the “fresh lock” fix from
above, and it carries the caveat from above: if the thread had been halfway through writing a record to
a stream, the child’s copy of that stream’s buffer has half a record in it.
Buffers are memory, and memory is copied:
import os
print("written once, before fork()")
pid = os.fork()
if pid:
os.waitpid(pid, 0)
$ python3 dup.py > dup_out.txt; cat dup_out.txt
written once, before fork()
written once, before fork()
$ python3 -u dup.py > dup_out.txt; cat dup_out.txt
written once, before fork()
Run in a terminal, this prints its line once, because sys.stdout on a terminal is line-buffered and the
line was written before the fork. Redirected to a file, sys.stdout is block-buffered: the line was still
in the io.BufferedWriter’s buffer in the parent’s memory when fork() copied it, and both processes
flushed their copy when they exited. -u makes the streams unbuffered. sys.stdout.flush() before the
fork is the targeted fix, and os._exit() in the child, which skips flushing, is the other half of the
habit.
State that should differ, and doesn’t
The standard library registers after-fork handlers of its own. threading uses one to forget every
thread but the caller and give the survivor fresh internal locks, which is why enumerate() was right in
the child above. And random uses one to reseed itself in the child, since 3.7. Before that, the child’s
generator was a byte-for-byte copy of the parent’s, and so was everything it would ever produce:
import os, random, sys
try:
import numpy
except ImportError:
numpy = None
r, w = os.pipe()
for _ in range(3):
if os.fork() == 0: # three children, each draws one number from each generator
line = "random %.6f" % random.random()
if numpy is not None:
line += " numpy.random %.6f" % numpy.random.random()
os.write(w, (line + "\n").encode())
os._exit(0)
for _ in range(3):
os.wait()
os.close(w)
print("Python", sys.version.split()[0], "" if numpy is None else "with NumPy " + numpy.__version__)
print(os.read(r, 4096).decode(), end="")
$ python3 randfork.py
Python 3.6.5
random 0.656073
random 0.656073
random 0.656073
That is Ubuntu 18.04’s own Python 3.6.5. Three children, three identical “random” numbers. On 20.04’s Python 3.8.2, with its NumPy 1.17.4:
$ python3 randfork.py
Python 3.8.2 with NumPy 1.17.4
random 0.860854 numpy.random 0.672156
random 0.152548 numpy.random 0.672156
random 0.559332 numpy.random 0.672156
random reseeded in each child; NumPy’s global generator, a C structure inside numpy.random, didn’t,
because nothing told it a fork had happened. A program that forks workers and has each draw random
samples with numpy.random gets the same samples in every worker, silently. The fix is to seed each
worker explicitly after the fork, from something that differs between them. Every library that keeps
state in C has this question to answer, and os.register_at_fork is the only hook CPython offers for it.
Three ways to start a worker
multiprocessing hides all of this behind a choice of start method. fork forks the parent as it is,
spawn starts a fresh interpreter with fork and exec and sends it what it needs through a pipe, and
forkserver spawns one clean server process early, then forks workers from that instead of from the
parent. Linux defaults to fork. Since 3.8, macOS defaults to spawn, the change Part 12 mentioned.
This script imports two modules at its top level, prints a line there, and then starts a pool of four
workers with each method:
import json, decimal, multiprocessing as mp, os, sys, time
print("top level of mpstart.py ran in", mp.current_process().name, flush=True)
def modules(_):
return len(sys.modules), "decimal" in sys.modules
if __name__ == "__main__":
for method in ("fork", "forkserver", "spawn"):
ctx = mp.get_context(method)
t = time.perf_counter()
with ctx.Pool(4) as pool:
r = pool.map(modules, range(4))
print("%-10s 4 workers started, used and stopped in %3.0f ms; a worker has %d modules, decimal: %s"
% (method, (time.perf_counter() - t) * 1000, r[0][0], r[0][1]), flush=True)
$ python3 mpstart.py
top level of mpstart.py ran in MainProcess
fork 4 workers started, used and stopped in 24 ms; a worker has 118 modules, decimal: True
top level of mpstart.py ran in ForkServerPoolWorker-5
top level of mpstart.py ran in ForkServerPoolWorker-6
top level of mpstart.py ran in ForkServerPoolWorker-7
top level of mpstart.py ran in ForkServerPoolWorker-8
forkserver 4 workers started, used and stopped in 33 ms; a worker has 131 modules, decimal: True
top level of mpstart.py ran in SpawnPoolWorker-9
top level of mpstart.py ran in SpawnPoolWorker-10
top level of mpstart.py ran in SpawnPoolWorker-11
top level of mpstart.py ran in SpawnPoolWorker-12
spawn 4 workers started, used and stopped in 22 ms; a worker has 130 modules, decimal: True
All three start quickly for a program this small. What differs is what a worker is. A fork worker is
the parent, copied: every module it had imported, every object it had built, every lock in whatever
state, and the top-level code didn’t run again. A spawn or forkserver worker is a new interpreter,
which can’t receive a function by reference, only by name. To find modules, it imports the main script
under the name __mp_main__, and so runs its top level again, once per worker, imports and print
included. That’s why the if __name__ == "__main__": guard is mandatory with spawn: without it each
worker would start its own pool. And that’s the trade. fork shares state, which is fast and is also
exactly the problem of the sections above. spawn shares nothing, and pays for it by running your
program’s top level again.
What a worker costs, and what it buys
Pool of 4 · ms to start, use, stop
The same loop, twice · seconds
Start-up times are one run each and moved by 10 ms between runs. Two processes halve the time; two subinterpreters in two threads don't, because they share one GIL.
Several interpreters in one process
CPython has supported more than one interpreter in a process for decades, through Py_NewInterpreter
in the C API: each subinterpreter has its own sys.modules, its own builtins, its own __main__.
Servers that embed Python, mod_wsgi in Apache for one, use them to keep applications apart. Python 3.8
added a module to use them from Python, _xxsubinterpreters, private and meant for testing the
proposal in PEP 554, which would make them public as a module called interpreters. PEP 554 is still a
draft.
import _xxsubinterpreters as interpreters, sys
x = 42
interp = interpreters.create()
print("interpreters:", interpreters.list_all(), flush=True)
print("main: %d modules, x = %r" % (len(sys.modules), x), flush=True)
interpreters.run_string(interp, "import sys; print('sub: %d modules, x defined: %s' % (len(sys.modules), 'x' in dir()), flush=True)")
show = "print('%-5s id(sys) %#x id(None) %#x id(int) %#x id(1) %#x' % (WHO, id(sys), id(None), id(int), id(1)), flush=True)"
WHO = "main:"
exec(show)
interpreters.run_string(interp, "import sys; WHO = 'sub:'\n" + show)
try:
interpreters.run_string(interp, "import os; os.fork()")
except interpreters.RunFailedError as e:
print("fork in the subinterpreter:", e, flush=True)
cid = interpreters.channel_create()
interpreters.run_string(interp, "import _xxsubinterpreters as i; i.channel_send(cid, b'hello from the subinterpreter')", shared={"cid": cid})
print("main received:", interpreters.channel_recv(cid), flush=True)
try:
interpreters.channel_send(cid, [1, 2, 3])
except Exception as e:
print("sending a list:", type(e).__name__, e, flush=True)
$ python3 subinterp.py
interpreters: [InterpreterID(0), InterpreterID(1)]
main: 34 modules, x = 42
sub: 32 modules, x defined: False
main: id(sys) 0x7a6457599e00 id(None) 0x5d8167522a60 id(int) 0x5d816751fc60 id(1) 0x5d816754e700
sub: id(sys) 0x7a6457471540 id(None) 0x5d8167522a60 id(int) 0x5d816751fc60 id(1) 0x5d816754e700
fork in the subinterpreter: <class 'RuntimeError'>: fork not supported for subinterpreters
main received: b'hello from the subinterpreter'
sending a list: ValueError [1, 2, 3] does not support cross-interpreter data
The subinterpreter has its own modules and its own sys, at a different address, and none of the main
interpreter’s variables. But None, int and the integer 1 are at the same addresses in both. They’re
not objects each interpreter created: None is a static C variable, _Py_NoneStruct, int is the
static PyLong_Type, and the small integers from Part 1 are one array for the whole process in 3.8. Every
interpreter increments and decrements the same ob_refcnt on None, many times a second. That’s the
reason subinterpreters in 3.8 share one GIL: without it, two interpreters running at once would race on
those reference counts. Sharing objects means sharing the lock, and the timing shows it:
import _xxsubinterpreters as interpreters, multiprocessing as mp, threading, time
work = "t = 0\nfor i in range(10_000_000): t += i"
procs = [mp.get_context("fork").Process(target=exec, args=(work,)) for _ in range(2)]
t = time.perf_counter()
for p in procs: p.start()
for p in procs: p.join()
print("two processes at once: %.2f s" % (time.perf_counter() - t))
a, b = interpreters.create(), interpreters.create() # after the fork: see below
t = time.perf_counter()
interpreters.run_string(a, work)
interpreters.run_string(b, work)
print("two interpreters, one after the other: %.2f s" % (time.perf_counter() - t))
t = time.perf_counter()
threads = [threading.Thread(target=interpreters.run_string, args=(i, work)) for i in (a, b)]
for th in threads: th.start()
for th in threads: th.join()
print("two interpreters, two threads at once: %.2f s" % (time.perf_counter() - t))
$ python3 subgil.py
two processes at once: 0.30 s
two interpreters, one after the other: 0.59 s
two interpreters, two threads at once: 0.58 s
Two processes ran the loop in parallel, in half the time. Two interpreters in two threads took exactly as
long as running them one after the other. The proposal behind PEP 554 is that one day each interpreter
gets its own GIL, which means first moving every piece of process-wide state, the static types, the
small integers, None, the allocator, the module copies Part 15 found in m_copy, into the
interpreter. That’s a long list, much of it in C extensions that don’t belong to CPython, and it’s why the
module is still private and called _xx.
The channel shows the other half of the design: interpreters don’t share Python objects at all, by
rule. A channel carries bytes, str, int and None, copied, and refuses a list.
When fork meets a subinterpreter
os.fork() refuses to run inside a subinterpreter, with an explicit error, since 3.8 (3.7.5’s
posixmodule.c has no such check). Forking from the
main interpreter while a subinterpreter exists is allowed, and subgil.py above forks its two processes
before it creates its interpreters for a reason. In the other order:
import _xxsubinterpreters as interpreters, os, sys, time
def fork_and_wait(label):
pid = os.fork()
if pid == 0:
os._exit(0) # the child does nothing at all
deadline = time.monotonic() + 3
while time.monotonic() < deadline:
if os.waitpid(pid, os.WNOHANG)[0]:
print("%-28s child exited" % label, flush=True)
return
time.sleep(0.05)
os.kill(pid, 9)
os.waitpid(pid, 0)
print("%-28s child still inside fork() after 3 s; killed" % label, flush=True)
print("Python", sys.version.split()[0], flush=True)
fork_and_wait("no subinterpreters:")
interp = interpreters.create()
fork_and_wait("one subinterpreter alive:")
interpreters.destroy(interp)
fork_and_wait("after destroying it:")
$ for v in 3.8.5 3.9.0rc1; do /opt/py/$v/bin/python3 forksub.py; done
Python 3.8.5
no subinterpreters: child exited
one subinterpreter alive: child still inside fork() after 3 s; killed
after destroying it: child exited
Python 3.9.0rc1
no subinterpreters: child exited
one subinterpreter alive: child still inside fork() after 3 s; killed
after destroying it: child exited
The child of the second fork never returns from os.fork(), on 3.8.5 or on 3.9’s first release
candidate. I found it the hard way, when the first version of subgil.py created its interpreters first
and never finished, and attached gdb to the stuck child:
(gdb) bt
#0 do_futex_wait.constprop () from /lib/x86_64-linux-gnu/libpthread.so.0
#1 __new_sem_wait_slow.constprop.0 () from /lib/x86_64-linux-gnu/libpthread.so.0
#2 PyThread_acquire_lock_timed (...) at Python/thread_pthread.h:459
#3 PyThread_acquire_lock (lock=..., waitflag=1) at Python/thread_pthread.h:697
#4 _PyInterpreterState_Clear (interp=..., runtime=...) at Python/pystate.c:261
#5 _PyInterpreterState_DeleteExceptMain (runtime=...) at Python/pystate.c:380
#6 PyOS_AfterFork_Child () at Modules/posixmodule.c:472
#7 os_fork_impl (module=...) at Modules/posixmodule.c:6179
(Addresses and argument values trimmed.) This is the line I asked you to remember. In the child,
PyOS_AfterFork_Child calls _PyInterpreterState_DeleteExceptMain to throw away the subinterpreter,
which the child can’t use. In Python/pystate.c at v3.8.5:
HEAD_LOCK(runtime);
PyInterpreterState *interp = interpreters->head;
interpreters->head = NULL;
while (interp != NULL) {
if (interp == interpreters->main) {
interpreters->main->next = NULL;
interpreters->head = interp;
interp = interp->next;
continue;
}
_PyInterpreterState_Clear(runtime, interp); // XXX must activate?
and _PyInterpreterState_Clear begins:
HEAD_LOCK(runtime);
for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
PyThreadState_Clear(p);
}
HEAD_UNLOCK(runtime);
HEAD_LOCK is PyThread_acquire_lock on the runtime’s list of interpreters, an ordinary lock that isn’t
re-entrant. The function takes it, then calls a function that takes it again, and waits for itself. It
only happens with a subinterpreter alive, which is why it hasn’t bitten many people. At the v3.9.0rc1
tag the code is reorganised but has the same shape: the lock is taken, then PyInterpreterState_Clear
is called, which takes it again. It’s been reported, as bpo-39958 in March, with the same backtrace,
by someone who hit it embedding Python, and is open as I write this. It is a fine small example of this
whole post: the child of a fork inherits a lock, and here the lock is CPython’s own, taken by CPython’s
own clean-up code.
A lock held across fork()
Who holds the lock, and who waits for it, second by second. The white line is the fork.
What we covered
fork()copies a process’s memory and one thread. A lock held by any other thread is held forever in the child:forklock.py’s child timed out after 5 s on a lock the parent released after 2.- CPython reinitialises its own locks after a fork (
PyOS_AfterFork_Child). For yours, 3.7’sos.register_at_forkcan take the lock before forking, at the cost of waiting for it. logging’s handler locks deadlocked a child on 3.7.0 and not on 3.8.5, which recreates them in the child. Unflushedprintoutput is copied too, and printed twice.randomreseeds in a forked child since 3.7; 3.6’s children drew identical numbers, and NumPy 1.17’s global generator still does.multiprocessing’sforkworkers are copies of the parent.spawnandforkserverworkers are fresh interpreters that rerun the main script’s top level.- Subinterpreters have their own modules but share every static object (
None,int, small integers) and so share the GIL: two of them in two threads took as long as running them in turn. - On 3.8.5 and 3.9.0rc1, a fork while a subinterpreter exists hangs the child inside
fork(), on a lock CPython’s clean-up takes twice, reported as bpo-39958.
The last post in this series looks at Python 3.9, due next month, at the plans for making CPython faster that have appeared this year, and back over everything this series measured.
A note on the evidence
What I ran, and where. CPython 3.8.5 and 3.9.0rc1 were built from their tags with Ubuntu 20.04’s gcc
9.3.0 and default ./configure options, in a chroot of 20.04 built with debootstrap from the release
archive; 3.7.0 is the build from Part 3, with 18.04’s gcc 7.3.0, in a chroot of 18.04. The chroots ran on
a newer host kernel, and everything here is about process memory and locks rather than the kernel.
randfork.py ran on the releases’ own python3 packages: 18.04’s 3.6.5 and 20.04’s 3.8.2 with
python3-numpy 1:1.17.4-5ubuntu3. Each
script was extracted from this page and run as shown, with outputs captured to files and pasted from
them. The gdb backtrace was taken with 20.04’s gdb 9.1 from the stuck child of the first version of
subgil.py, and trimmed as stated.
The numbers. The lock and fork timings are set by the scripts’ own sleeps and timeouts. The start-method
times are one run of a pool of four, small and noisy: across three runs fork took 11 to 24 ms and the
other two 22 to 33 ms, so I don’t rank them. The CPU-work times are one run each. Across four runs the two
subinterpreter timings ranged from 0.57 to 0.65 s and stayed within 0.02 s of each other in every run,
and the two processes took 0.29 or 0.30 s. A complete rerun of every command on this page, extracted from
the page, reproduced every result: the same timeout, the same logging outcome on 3.7.0 and 3.8.5, the
duplicated line, identical random numbers on 3.6.5 and identical NumPy numbers on 3.8.2, and the same
stuck child on both versions.
What I read rather than ran. PyOS_BeforeFork, PyOS_AfterFork_Child and the subinterpreter checks in
os.fork are from Modules/posixmodule.c, and the interpreter clean-up from Python/pystate.c, at
v3.8.5 and v3.9.0rc1. The logging change is from Lib/logging/__init__.py: absent at v3.7.0, in part at
v3.7.1, and in its current form by v3.7.5; I didn’t run the releases in between. bpo-39958 is on
bugs.python.org, filed 13 March 2020, with no fix linked as of this writing. PEP 554’s status is from the
PEP. That None, int and the small integers are static in 3.8 is from Objects/object.c,
Objects/longobject.c and the matching addresses above.
Not covered. Threads and fork on macOS, where the system libraries are less forgiving than glibc and
which is why its default became spawn. os.posix_spawn, new in 3.8. And the C API side of
subinterpreters, Py_NewInterpreter and Py_EndInterpreter, which this post only names.
Fork, Threads and Other Interpreters