# Feature or enhancement The `set` object is not currently thread-safe in `--disable-gil` builds. We should make it thread-safe by using the ["critical section" API](https://github.com/python/cpython/blob/0ff6368519ed7542ad8b443de01108690102420a/Include/internal/pycore_critical_section.h). to acquire the per-object locks around operations. There should be no effective change in the default build (i.e., with GIL) because critical sections are no-ops in the default build. **Notes**: 1. Unlike `dict` and `list`, I don't think it's worth the complexity to try to "optimistically avoid locking" around any set operation (except `set_len`). We could consider doing this in the future if there is a performance justification, but not for 3.13. 2. `set_len` can avoid locking and instead use relaxed atomics for reading the "used" field. Note that writes to "used" should then also use relaxed atomics. 3. Some operations require locking two containers (like `set_merge`). Some of these will need refactorings so that the critical sections macros can be added in the correct places. For context, here is the change from the `nogil-3.12` fork: https://github.com/colesbury/nogil-3.12/commit/4ca2924f0d. Note that the critical section API is slightly changed in 3.13 from `nogil-3.12`; In 3.13 `Py_BEGIN_CRITICAL_SECTION` takes a PyObject instead of a PyMutex. ### TODO: - [x] Improve `set_init` (see https://github.com/python/cpython/pull/113800#discussion_r1517017947). We also want to avoid locking in `set_init` if possible - [x] `_PySet_NextEntry` - [x] `setiter_iternext` <!-- gh-linked-prs --> ### Linked PRs * gh-113800 * gh-115112 * gh-116525 * gh-117935 * gh-117990 * gh-118053 * gh-118069 <!-- /gh-linked-prs -->