Skip to content

Commit 880afcf

Browse files
committed
pythongh-114271: Make the common usage of _thread.lock thread-safe in free-threaded builds
Previously, the `locked` field was set after releasing the lock. This reverses the order so that the `locked` field is set while the lock is still held. There is still one thread-safety issue where `locked` is checked prior to releasing the lock, however, in practice that will only be an issue when unlocking the lock is contended, which should be rare.
1 parent 73807eb commit 880afcf

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

Modules/_threadmodule.c

+2-2
Original file line numberDiff line numberDiff line change
@@ -390,8 +390,8 @@ lock_PyThread_release_lock(lockobject *self, PyObject *Py_UNUSED(ignored))
390390
return NULL;
391391
}
392392

393-
PyThread_release_lock(self->lock_lock);
394393
self->locked = 0;
394+
PyThread_release_lock(self->lock_lock);
395395
Py_RETURN_NONE;
396396
}
397397

@@ -1665,8 +1665,8 @@ release_sentinel(void *weakref_raw)
16651665
lockobject *lock = (lockobject *)_PyWeakref_GET_REF(weakref);
16661666
if (lock != NULL) {
16671667
if (lock->locked) {
1668-
PyThread_release_lock(lock->lock_lock);
16691668
lock->locked = 0;
1669+
PyThread_release_lock(lock->lock_lock);
16701670
}
16711671
Py_DECREF(lock);
16721672
}

0 commit comments

Comments
 (0)