Fast Re-entrant Optimistic Lock
Fastrlock is a C-level implementation of a re-entrant, optimistic lock for CPython, serving as a drop-in replacement for `threading.RLock`. Implemented in Cython, it offers both a Python and a C-API, designed to optimize for non-congested locking scenarios. It is actively maintained with periodic updates to support newer Python versions, with its current version being 0.8.3.
Warnings
- gotcha Performance comparison with `threading.RLock` in Python 3.4+ may be mixed. While `fastrlock` is generally faster in Python 2.7 and through its Cython API, for Python 3.4 and later, the standard library's `threading.RLock` can be as fast or even faster when called through the Python API.
- deprecated Official Python 2 support has been removed, although Linux wheels for Python 2 might still be built for legacy reasons. New development focuses on Python 3.
- breaking Version 0.7 included an adaptation for unsigned thread IDs, which are used by Python 3.7 and newer. While primarily an internal change, using versions prior to 0.7 with Python 3.7+ could potentially lead to unexpected behavior related to thread identification.
- gotcha The primary performance benefit of `fastrlock` in modern Python versions (3.4+) is realized when utilizing its C-API directly from other Cython modules, as this avoids Python call overhead. Using it purely through its Python API might yield less significant or no performance gains compared to the standard library's `threading.RLock`.
Install
-
pip install fastrlock
Imports
- rlock
from fastrlock import rlock
Quickstart
import threading
from fastrlock import rlock
def worker(lock, name):
print(f"{name}: Trying to acquire lock...")
with lock:
print(f"{name}: Lock acquired. Doing work...")
# Simulate re-entrant acquisition
with lock:
print(f"{name}: Lock re-acquired internally.")
print(f"{name}: Work done, releasing lock.")
# Using fastrlock
fast_lock = rlock()
thread1 = threading.Thread(target=worker, args=(fast_lock, "Thread A"))
thread2 = threading.Thread(target=worker, args=(fast_lock, "Thread B"))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("All threads finished.")