Skip to content

Commit de7d67b

Browse files
authored
gh-114271: Make PyInterpreterState.threads.count thread-safe in free-threaded builds (gh-115093)
Use atomics to mutate PyInterpreterState.threads.count.
1 parent 879f454 commit de7d67b

File tree

2 files changed

+4
-4
lines changed

2 files changed

+4
-4
lines changed

Include/internal/pycore_interp.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ struct _is {
112112
/* The thread currently executing in the __main__ module, if any. */
113113
PyThreadState *main;
114114
/* Used in Modules/_threadmodule.c. */
115-
long count;
115+
Py_ssize_t count;
116116
/* Support for runtime thread stack size tuning.
117117
A value of 0 means using the platform's default stack size
118118
or the size specified by the THREAD_STACK_SIZE macro. */

Modules/_threadmodule.c

+3-3
Original file line numberDiff line numberDiff line change
@@ -1244,7 +1244,7 @@ thread_run(void *boot_raw)
12441244

12451245
_PyThreadState_Bind(tstate);
12461246
PyEval_AcquireThread(tstate);
1247-
tstate->interp->threads.count++;
1247+
_Py_atomic_add_ssize(&tstate->interp->threads.count, 1);
12481248

12491249
PyObject *res = PyObject_Call(boot->func, boot->args, boot->kwargs);
12501250
if (res == NULL) {
@@ -1262,7 +1262,7 @@ thread_run(void *boot_raw)
12621262

12631263
thread_bootstate_free(boot, 1);
12641264

1265-
tstate->interp->threads.count--;
1265+
_Py_atomic_add_ssize(&tstate->interp->threads.count, -1);
12661266
PyThreadState_Clear(tstate);
12671267
_PyThreadState_DeleteCurrent(tstate);
12681268

@@ -1539,7 +1539,7 @@ static PyObject *
15391539
thread__count(PyObject *self, PyObject *Py_UNUSED(ignored))
15401540
{
15411541
PyInterpreterState *interp = _PyInterpreterState_GET();
1542-
return PyLong_FromLong(interp->threads.count);
1542+
return PyLong_FromSsize_t(_Py_atomic_load_ssize(&interp->threads.count));
15431543
}
15441544

15451545
PyDoc_STRVAR(_count_doc,

0 commit comments

Comments
 (0)