SIGN IN SIGN UP

[mypyc] Add librt.threading.Lock class (#21690)

The new native `Lock` class is a partial replacement for
`threading.Lock`. It's much faster than `threading.Lock` in compiled
code. In a microbenchmark I saw ~2.5x to ~4x performance improvement
over compiled code using stdlib.

The Lock type has four platform-specific backends:
- PyMutex on Python 3.14+ (all platforms); uses CPython's internal
1-byte atomic lock
 - SRWLOCK + condition variable on Windows < 3.14
 - POSIX semaphore on Linux < 3.14 with GIL
 - pthread mutex + condvar fallback (macOS, free-threaded builds)

All backends preserve threading.Lock semantics (cross-thread release
allowed) and drop the GIL while blocking.

Added optimized handling of `with lock:` statements (for
`librt.threading` only).

There is one significant known regression compared to CPython (beyond
missing features): if two threads race to release the same lock, this
triggers undefined behavior. The PyMutex C API doesn't provide a way to
avoid this without a massive performance cost, so I decided to keep this
limitation instead of sacrificing performance, as performance is the
main goal of the new type.

This is just a lock -- using it with `threading.Condition` is not
supported. We may later decide to add a native `Condition` (and possibly
other synchronization primitives).

I used heavy coding agent assist with small, incremental changes, and
multiple review iterations. I left the rather verbose comments generated
by coding agents, since the code is legitimately tricky.

---------

Co-authored-by: Piotr Sawicki <sawickipiotr@outlook.com>
J
Jukka Lehtosalo committed
f3294a092bd2f43979bc1d83e3f27e1c2e0a1453
Parent: cfc0734
Committed by GitHub <noreply@github.com> on 7/7/2026, 5:41:19 PM