Skip to content

Commit

Permalink
gh-114271: Make _thread.lock thread-safe in free-threaded builds (#…
Browse files Browse the repository at this point in the history
…116433)

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.
  • Loading branch information
mpage authored Mar 6, 2024
1 parent ce0ae1d commit c62144a
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Modules/_threadmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -390,8 +390,8 @@ lock_PyThread_release_lock(lockobject *self, PyObject *Py_UNUSED(ignored))
return NULL;
}

PyThread_release_lock(self->lock_lock);
self->locked = 0;
PyThread_release_lock(self->lock_lock);
Py_RETURN_NONE;
}

Expand Down Expand Up @@ -1665,8 +1665,8 @@ release_sentinel(void *weakref_raw)
lockobject *lock = (lockobject *)_PyWeakref_GET_REF(weakref);
if (lock != NULL) {
if (lock->locked) {
PyThread_release_lock(lock->lock_lock);
lock->locked = 0;
PyThread_release_lock(lock->lock_lock);
}
Py_DECREF(lock);
}
Expand Down

0 comments on commit c62144a

Please sign in to comment.