gh-111924: Use PyMutex for Runtime-global Locks. (gh-112207)

This replaces some usages of PyThread_type_lock with PyMutex, which does not require memory allocation to initialize.

This simplifies some of the runtime initialization and is also one step towards avoiding changing the default raw memory allocator during initialize/finalization, which can be non-thread-safe in some circumstances.
This commit is contained in:
Sam Gross 2023-12-07 14:33:40 -05:00 committed by GitHub
parent db460735af
commit cf6110ba13
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 97 additions and 241 deletions

View file

@ -456,16 +456,17 @@ _xidregistry_clear(struct _xidregistry *xidregistry)
static void
_xidregistry_lock(struct _xidregistry *registry)
{
if (registry->mutex != NULL) {
PyThread_acquire_lock(registry->mutex, WAIT_LOCK);
if (registry->global) {
PyMutex_Lock(&registry->mutex);
}
// else: Within an interpreter we rely on the GIL instead of a separate lock.
}
static void
_xidregistry_unlock(struct _xidregistry *registry)
{
if (registry->mutex != NULL) {
PyThread_release_lock(registry->mutex);
if (registry->global) {
PyMutex_Unlock(&registry->mutex);
}
}
@ -874,19 +875,10 @@ _xidregistry_init(struct _xidregistry *registry)
registry->initialized = 1;
if (registry->global) {
// We manage the mutex lifecycle in pystate.c.
assert(registry->mutex != NULL);
// Registering the builtins is cheap so we don't bother doing it lazily.
assert(registry->head == NULL);
_register_builtins_for_crossinterpreter_data(registry);
}
else {
// Within an interpreter we rely on the GIL instead of a separate lock.
assert(registry->mutex == NULL);
// There's nothing else to initialize.
}
}
static void
@ -898,17 +890,6 @@ _xidregistry_fini(struct _xidregistry *registry)
registry->initialized = 0;
_xidregistry_clear(registry);
if (registry->global) {
// We manage the mutex lifecycle in pystate.c.
assert(registry->mutex != NULL);
}
else {
// There's nothing else to finalize.
// Within an interpreter we rely on the GIL instead of a separate lock.
assert(registry->mutex == NULL);
}
}