Skip to content

Commit 7274538

Browse files
committed
Make PyInterpreterState.threads.count thread-safe in free-threaded builds
Use atomics
1 parent c32bae5 commit 7274538

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
@@ -1225,7 +1225,7 @@ thread_run(void *boot_raw)
12251225

12261226
_PyThreadState_Bind(tstate);
12271227
PyEval_AcquireThread(tstate);
1228-
tstate->interp->threads.count++;
1228+
_Py_atomic_add_ssize(&tstate->interp->threads.count, 1);
12291229

12301230
PyObject *res = PyObject_Call(boot->func, boot->args, boot->kwargs);
12311231
if (res == NULL) {
@@ -1243,7 +1243,7 @@ thread_run(void *boot_raw)
12431243

12441244
thread_bootstate_free(boot, 1);
12451245

1246-
tstate->interp->threads.count--;
1246+
_Py_atomic_add_ssize(&tstate->interp->threads.count, -1);
12471247
PyThreadState_Clear(tstate);
12481248
_PyThreadState_DeleteCurrent(tstate);
12491249

@@ -1520,7 +1520,7 @@ static PyObject *
15201520
thread__count(PyObject *self, PyObject *Py_UNUSED(ignored))
15211521
{
15221522
PyInterpreterState *interp = _PyInterpreterState_GET();
1523-
return PyLong_FromLong(interp->threads.count);
1523+
return PyLong_FromSsize_t(_Py_atomic_load_ssize(&interp->threads.count));
15241524
}
15251525

15261526
PyDoc_STRVAR(_count_doc,

0 commit comments

Comments
 (0)