diff options
author | Lysandros Nikolaou <lisandrosnik@gmail.com> | 2024-08-06 11:29:57 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-08-06 11:29:57 (GMT) |
commit | ce0d66c8d238c9676c6ecd3f04294a3299e07f74 (patch) | |
tree | d45805d8c6dd228df48a38d653174886815332cb /Parser | |
parent | a8be8fc6c4682089be45a87bd5ee1f686040116c (diff) | |
download | cpython-ce0d66c8d238c9676c6ecd3f04294a3299e07f74.zip cpython-ce0d66c8d238c9676c6ecd3f04294a3299e07f74.tar.gz cpython-ce0d66c8d238c9676c6ecd3f04294a3299e07f74.tar.bz2 |
gh-122581: Avoid data races when collecting parser statistics (#122694)
Diffstat (limited to 'Parser')
-rw-r--r-- | Parser/pegen.c | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/Parser/pegen.c b/Parser/pegen.c index ac428be..0c3c468 100644 --- a/Parser/pegen.c +++ b/Parser/pegen.c @@ -296,12 +296,22 @@ error: #define NSTATISTICS _PYPEGEN_NSTATISTICS #define memo_statistics _PyRuntime.parser.memo_statistics +#ifdef Py_GIL_DISABLED +#define MUTEX_LOCK() PyMutex_Lock(&_PyRuntime.parser.mutex) +#define MUTEX_UNLOCK() PyMutex_Unlock(&_PyRuntime.parser.mutex) +#else +#define MUTEX_LOCK() +#define MUTEX_UNLOCK() +#endif + void _PyPegen_clear_memo_statistics(void) { + MUTEX_LOCK(); for (int i = 0; i < NSTATISTICS; i++) { memo_statistics[i] = 0; } + MUTEX_UNLOCK(); } PyObject * @@ -311,18 +321,23 @@ _PyPegen_get_memo_statistics(void) if (ret == NULL) { return NULL; } + + MUTEX_LOCK(); for (int i = 0; i < NSTATISTICS; i++) { PyObject *value = PyLong_FromLong(memo_statistics[i]); if (value == NULL) { + MUTEX_UNLOCK(); Py_DECREF(ret); return NULL; } // PyList_SetItem borrows a reference to value. if (PyList_SetItem(ret, i, value) < 0) { + MUTEX_UNLOCK(); Py_DECREF(ret); return NULL; } } + MUTEX_UNLOCK(); return ret; } #endif @@ -348,7 +363,9 @@ _PyPegen_is_memoized(Parser *p, int type, void *pres) if (count <= 0) { count = 1; } + MUTEX_LOCK(); memo_statistics[type] += count; + MUTEX_UNLOCK(); } #endif p->mark = m->mark; |