Skip to content

Commit

Permalink
pythongh-129185: Simplify PyTraceMalloc_Track() (python#129256)
Browse files Browse the repository at this point in the history
Since tracemalloc uses PyMutex, it becomes safe to use TABLES_LOCK()
even after _PyTraceMalloc_Fini(): remove the "pre-check" in
PyTraceMalloc_Track() and PyTraceMalloc_Untrack().

PyTraceMalloc_Untrack() no longer needs to acquire the GIL.

_PyTraceMalloc_Fini() can be called earlier during Python
finalization.
  • Loading branch information
vstinner authored Jan 24, 2025
1 parent 233fd00 commit fc6bc1e
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 26 deletions.
3 changes: 1 addition & 2 deletions Python/pylifecycle.c
Original file line number Diff line number Diff line change
Expand Up @@ -2113,7 +2113,7 @@ _Py_Finalize(_PyRuntimeState *runtime)

/* Disable tracemalloc after all Python objects have been destroyed,
so it is possible to use tracemalloc in objects destructor. */
_PyTraceMalloc_Stop();
_PyTraceMalloc_Fini();

/* Finalize any remaining import state */
// XXX Move these up to where finalize_modules() is currently.
Expand Down Expand Up @@ -2166,7 +2166,6 @@ _Py_Finalize(_PyRuntimeState *runtime)

finalize_interp_clear(tstate);

_PyTraceMalloc_Fini();

#ifdef Py_TRACE_REFS
/* Display addresses (& refcnts) of all objects still alive.
Expand Down
26 changes: 2 additions & 24 deletions Python/tracemalloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -1203,17 +1203,9 @@ PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr,
size_t size)
{
PyGILState_STATE gil_state = PyGILState_Ensure();
int result;

// gh-129185: Check before TABLES_LOCK() to support calls after
// _PyTraceMalloc_Fini().
if (!tracemalloc_config.tracing) {
result = -2;
goto done;
}

TABLES_LOCK();

int result;
if (tracemalloc_config.tracing) {
result = tracemalloc_add_trace_unlocked(domain, ptr, size);
}
Expand All @@ -1223,29 +1215,17 @@ PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr,
}

TABLES_UNLOCK();
done:
PyGILState_Release(gil_state);

return result;
}


int
PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
{
// Need the GIL to prevent races on the first 'tracing' test
PyGILState_STATE gil_state = PyGILState_Ensure();
int result;

// gh-129185: Check before TABLES_LOCK() to support calls after
// _PyTraceMalloc_Fini()
if (!tracemalloc_config.tracing) {
result = -2;
goto done;
}

TABLES_LOCK();

int result;
if (tracemalloc_config.tracing) {
tracemalloc_remove_trace_unlocked(domain, ptr);
result = 0;
Expand All @@ -1256,8 +1236,6 @@ PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
}

TABLES_UNLOCK();
done:
PyGILState_Release(gil_state);
return result;
}

Expand Down

0 comments on commit fc6bc1e

Please sign in to comment.