Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Include/internal/pycore_tracemalloc.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ struct _PyTraceMalloc_Config {
} initialized;

/* Is tracemalloc tracing memory allocations?
Variable protected by the TABLES_LOCK(). */
Variable protected by the TABLES_LOCK() and stored atomically.
Atomic store is used so that it can read without locking for the
general case of checking if tracemalloc is enabled.
*/
int tracing;

/* limit of the number of frames in a traceback, 1 by default.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Avoid locking in :c:func:`PyTraceMalloc_Track` when :mod:`tracemalloc` is not enabled.
13 changes: 11 additions & 2 deletions Python/tracemalloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,7 @@ _PyTraceMalloc_Start(int max_nframe)

/* everything is ready: start tracing Python memory allocations */
TABLES_LOCK();
tracemalloc_config.tracing = 1;
_Py_atomic_store_int_relaxed(&tracemalloc_config.tracing, 1);
TABLES_UNLOCK();

return 0;
Expand All @@ -867,7 +867,7 @@ _PyTraceMalloc_Stop(void)
}

/* stop tracing Python memory allocations */
tracemalloc_config.tracing = 0;
_Py_atomic_store_int_relaxed(&tracemalloc_config.tracing, 0);

/* unregister the hook on memory allocators */
PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &allocators.raw);
Expand Down Expand Up @@ -1207,6 +1207,10 @@ int
PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr,
size_t size)
{
if (_Py_atomic_load_int_relaxed(&tracemalloc_config.tracing) == 0) {
/* tracemalloc is not tracing: do nothing */
return -2;
}
PyGILState_STATE gil_state = PyGILState_Ensure();
TABLES_LOCK();

Expand All @@ -1228,6 +1232,11 @@ PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr,
int
PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
{
if (_Py_atomic_load_int_relaxed(&tracemalloc_config.tracing) == 0) {
/* tracemalloc is not tracing: do nothing */
return -2;
}

TABLES_LOCK();

int result;
Expand Down
Loading