Skip to content

Commit c005ea4

Browse files
authored
gh-129185: Use PyMutex in tracemalloc (#129246)
1 parent 36bb229 commit c005ea4

File tree

2 files changed

+4
-15
lines changed

2 files changed

+4
-15
lines changed

Include/internal/pycore_tracemalloc.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ struct _tracemalloc_runtime_state {
7070
PyMemAllocatorEx obj;
7171
} allocators;
7272

73-
PyThread_type_lock tables_lock;
73+
PyMutex tables_lock;
7474
/* Size in bytes of currently traced memory.
7575
Protected by TABLES_LOCK(). */
7676
size_t traced_memory;

Python/tracemalloc.c

+3-14
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "pycore_gc.h" // PyGC_Head
44
#include "pycore_hashtable.h" // _Py_hashtable_t
55
#include "pycore_initconfig.h" // _PyStatus_NO_MEMORY()
6+
#include "pycore_lock.h" // PyMutex_LockFlags()
67
#include "pycore_object.h" // _PyType_PreHeaderSize()
78
#include "pycore_pymem.h" // _Py_tracemalloc_config
89
#include "pycore_runtime.h" // _Py_ID()
@@ -37,8 +38,8 @@ static int _PyTraceMalloc_TraceRef(PyObject *op, PyRefTracerEvent event,
3738
the GIL held from PyMem_RawFree(). It cannot acquire the lock because it
3839
would introduce a deadlock in _PyThreadState_DeleteCurrent(). */
3940
#define tables_lock _PyRuntime.tracemalloc.tables_lock
40-
#define TABLES_LOCK() PyThread_acquire_lock(tables_lock, 1)
41-
#define TABLES_UNLOCK() PyThread_release_lock(tables_lock)
41+
#define TABLES_LOCK() PyMutex_LockFlags(&tables_lock, _Py_LOCK_DONT_DETACH)
42+
#define TABLES_UNLOCK() PyMutex_Unlock(&tables_lock)
4243

4344

4445
#define DEFAULT_DOMAIN 0
@@ -741,13 +742,6 @@ _PyTraceMalloc_Init(void)
741742
return _PyStatus_NO_MEMORY();
742743
}
743744

744-
if (tables_lock == NULL) {
745-
tables_lock = PyThread_allocate_lock();
746-
if (tables_lock == NULL) {
747-
return _PyStatus_NO_MEMORY();
748-
}
749-
}
750-
751745
tracemalloc_filenames = hashtable_new(hashtable_hash_pyobject,
752746
hashtable_compare_unicode,
753747
tracemalloc_clear_filename, NULL);
@@ -792,11 +786,6 @@ tracemalloc_deinit(void)
792786
_Py_hashtable_destroy(tracemalloc_tracebacks);
793787
_Py_hashtable_destroy(tracemalloc_filenames);
794788

795-
if (tables_lock != NULL) {
796-
PyThread_free_lock(tables_lock);
797-
tables_lock = NULL;
798-
}
799-
800789
PyThread_tss_delete(&tracemalloc_reentrant_key);
801790
}
802791

0 commit comments

Comments
 (0)