@@ -850,7 +850,7 @@ _PyTraceMalloc_Start(int max_nframe)
850850
851851 /* everything is ready: start tracing Python memory allocations */
852852 TABLES_LOCK ();
853- tracemalloc_config .tracing = 1 ;
853+ _Py_atomic_store_int_relaxed ( & tracemalloc_config .tracing , 1 ) ;
854854 TABLES_UNLOCK ();
855855
856856 return 0 ;
@@ -867,7 +867,7 @@ _PyTraceMalloc_Stop(void)
867867 }
868868
869869 /* stop tracing Python memory allocations */
870- tracemalloc_config .tracing = 0 ;
870+ _Py_atomic_store_int_relaxed ( & tracemalloc_config .tracing , 0 ) ;
871871
872872 /* unregister the hook on memory allocators */
873873 PyMem_SetAllocator (PYMEM_DOMAIN_RAW , & allocators .raw );
@@ -1207,18 +1207,13 @@ int
12071207PyTraceMalloc_Track (unsigned int domain , uintptr_t ptr ,
12081208 size_t size )
12091209{
1210- PyGILState_STATE gil_state = PyGILState_Ensure ();
1211- TABLES_LOCK ();
1212-
1213- int result ;
1214- if (tracemalloc_config .tracing ) {
1215- result = tracemalloc_add_trace_unlocked (domain , ptr , size );
1216- }
1217- else {
1210+ if (_Py_atomic_load_int_relaxed (& tracemalloc_config .tracing ) == 0 ) {
12181211 /* tracemalloc is not tracing: do nothing */
1219- result = -2 ;
1212+ return -2 ;
12201213 }
1221-
1214+ PyGILState_STATE gil_state = PyGILState_Ensure ();
1215+ TABLES_LOCK ();
1216+ int result = tracemalloc_add_trace_unlocked (domain , ptr , size );
12221217 TABLES_UNLOCK ();
12231218 PyGILState_Release (gil_state );
12241219 return result ;
@@ -1228,20 +1223,15 @@ PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr,
12281223int
12291224PyTraceMalloc_Untrack (unsigned int domain , uintptr_t ptr )
12301225{
1231- TABLES_LOCK ();
1232-
1233- int result ;
1234- if (tracemalloc_config .tracing ) {
1235- tracemalloc_remove_trace_unlocked (domain , ptr );
1236- result = 0 ;
1237- }
1238- else {
1226+ if (_Py_atomic_load_int_relaxed (& tracemalloc_config .tracing ) == 0 ) {
12391227 /* tracemalloc is not tracing: do nothing */
1240- result = -2 ;
1228+ return -2 ;
12411229 }
12421230
1231+ TABLES_LOCK ();
1232+ tracemalloc_remove_trace_unlocked (domain , ptr );
12431233 TABLES_UNLOCK ();
1244- return result ;
1234+ return 0 ;
12451235}
12461236
12471237
0 commit comments