python / cpython

The Python programming language
https://www.python.org
Other
63.65k stars 30.49k forks source link

gh-126688: Support Fork Parent and Child With Different Thread ID #127121

Open ericsnowcurrently opened 4 days ago

ericsnowcurrently commented 4 days ago

gh-126692 took care of one situation where we were assuming the thread ID did not change across fork. However, there is at least one other, in PyOS_AfterFork_Child(). This PR addresses that case along with making the parent's thread ID available to the child.

Here's a breakdown:

I've also moved the _PyImport_ReInitLock() call from PyOS_AfterFork_Child() to _PyRuntimeState_ReInitThreads(), to be more consistent about where we reinitialize locks after forking. If there are any objections, I don't mind dropping that part.

One motivation I have here is that I'd like to use a _PyRecursiveMutex elsewhere and need to be able to correctly reinitialize after forking. That requires knowing the parent's thread ID, to decide if the forking thread held the lock or not. (This wasn't a problem for the import lock, which is a _PyRecursiveMutex, since we always acquire and hold that lock while forking.)

@gpshead, I'd be particularly interested in your thoughts on this.