🔒 lock#
Inter-process locks implementing First-In-First-Out (FIFO).
Source:
Provides three classes:
LockFifo: basic cross-process lock using filesystem (POSIX via fcntl, Windows via msvcrt).RLockFifo: reentrant per-(process,thread) lock built on top ofLockFifo.RedisLockFifo: distributed lock using redis (optional dependency).
Usage#
>>> import stouputils as stp
>>> with stp.LockFifo("some_directory/my.lock", timeout=5):
... pass
>>> with stp.RLockFifo("some_directory/my_r.lock", timeout=5):
... pass
>>> def _redis_example():
... with stp.RedisLockFifo("my_redis_lock", timeout=5):
... pass
>>> import os
>>> if os.name != "nt":
... _redis_example()
import time
import stouputils as stp
def write_report(worker: int) -> None:
# One process at a time enters this block, in the order they asked for the lock
with stp.LockFifo("report.lock"):
stp.info(f"Worker {worker} writes the report")
time.sleep(0.3)
# Needed because each new process imports this file again
if __name__ == "__main__":
# Start 6 processes that all want the lock at once
stp.multiprocessing(write_report, range(6), max_workers=6)
base#
- class LockFifo(
- name: str,
- timeout: float | None = None,
- blocking: bool = True,
- check_interval: float = 0.05,
- fifo: bool = True,
- fifo_stale_timeout: float | None = None,
Bases:
AbstractContextManager[LockFifo]A simple cross-platform inter-process lock backed by a file.
This implementation supports optional Fifo ordering via a small ticket queue stored alongside the lock file. Fifo is enabled by default to avoid starvation. Fifo behaviour is implemented with a small sequence file and per-ticket files in
<lockpath>.queue/.- Parameters:
name – Lock filename or path. If a simple name is given, it is created in the system temporary directory.
timeout – Seconds to wait for the lock.
Nonemeans block indefinitely.blocking – Whether to block until acquired (subject to
timeout).check_interval – Interval between lock attempts, in seconds.
fifo – Whether to enforce Fifo ordering (default: True).
fifo_stale_timeout – Seconds after which a ticket is considered stale; if
Nonethe lock’stimeoutvalue will be used.
- Raises:
LockTimeoutError – If the lock could not be acquired within the timeout (LockError & TimeoutError subclass)
LockError – On unexpected locking errors. (RunTimeError subclass)
>>> # Basic context-manager usage (Fifo enabled by default) >>> with LockFifo("my.lock", timeout=1): ... pass
>>> # Explicit acquire/release >>> lock = LockFifo("my.lock", timeout=1) >>> lock.acquire() >>> lock.release()
>>> # Doctest: simple multi-process Fifo check (fast and deterministic) >>> import tempfile, multiprocessing, time >>> tmpdir = tempfile.mkdtemp() >>> lockpath = tmpdir + "/t.lock" >>> out = tmpdir + "/out.txt" >>> # Worker function is module-level: `_worker` >>> # (Defined at module scope so it can be pickled on Windows) >>> procs = [] >>> for i in range(3): ... p = multiprocessing.Process(target=_worker, args=(lockpath, out, i, i * 0.05)) ... p.start(); procs.append(p) >>> for p in procs: p.join(1) >>> with open(out) as f: print([int(x) for x in f.read().splitlines()]) [0, 1, 2]
>>> # Doctest: cleanup of artifacts on close >>> import tempfile, os >>> tmp = tempfile.mkdtemp() >>> p = tmp + "/tlock" >>> l = LockFifo(p, timeout=1) >>> l.acquire(); l.release(); l.close() >>> import os >>> # The lock file should not remain on any platform after close() >>> assert not os.path.exists(p) >>> assert not os.path.exists(p + ".queue")
>>> # Non-Fifo fast-path should not create a queue directory >>> tmp2 = tempfile.mkdtemp() >>> p2 = tmp2 + "/tlock2" >>> l2 = LockFifo(p2, fifo=False, timeout=1) >>> l2.acquire(); l2.release(); l2.close() >>> os.path.exists(p2 + ".queue") False
>>> # Attempting a non-blocking acquire while another process holds the lock raises LockTimeoutError >>> import multiprocessing, time >>> # Hold function is module-level: `_hold` >>> # (Defined at module scope so it can be pickled on Windows) >>> p = multiprocessing.Process(target=_hold, args=(p2,)) >>> p.start() >>> import time, os >>> deadline = time.time() + 1.0 >>> while not os.path.exists(p2 + ".held") and time.time() < deadline: ... time.sleep(0.01) >>> from stouputils.lock import LockTimeoutError >>> l3 = LockFifo(p2, timeout=1) >>> try: ... l3.acquire(blocking=False) ... except LockTimeoutError: ... print("timeout") ... finally: ... p.terminate(); p.join() timeout
- timeout: float | None[source]#
Maximum time to wait for the lock, in seconds. None means wait indefinitely.
- fifo_stale_timeout: float | None[source]#
Seconds to consider a ticket stale and eligible for cleanup. If
None, the lock’stimeoutvalue will be used; if that is alsoNone, no stale cleanup will be performed.
- get_ticket() int[source]#
Obtain a monotonically increasing ticket number. Delegates to the queue backend when available.
- perform_lock(
- blocking: bool,
- timeout: float | None,
- check_interval: float,
Take the OS lock on the lock file, retrying until the deadline. Used by both Fifo and non-Fifo paths.
- acquire(
- timeout: float | None = None,
- blocking: bool | None = None,
- check_interval: float | None = None,
Acquire the lock, optionally using Fifo ordering.
When Fifo is enabled (default), a ticket file is created and the caller waits until its ticket becomes head of the queue before attempting the actual underlying lock. This avoids starvation by ensuring waiters are served in arrival order.
- close() None[source]#
Release and close underlying file descriptor.
Also attempts best-effort cleanup of queue artifacts and the lock file itself when it is safe to do so (no waiting clients and the lock is not held). This avoids leaving behind
<lock>.queue/and<lock>files when they are no longer in use.
queue#
- class BaseTicketQueue[source]#
Bases:
objectBase API for ticket queues.
- register() tuple[int, str][source]#
Function ‘register()’ is abstract and must be implemented by a subclass
- is_head(ticket: int) bool[source]#
Function ‘is_head()’ is abstract and must be implemented by a subclass
- remove(member: str) None[source]#
Function ‘remove()’ is abstract and must be implemented by a subclass
- cleanup_stale() None[source]#
Function ‘cleanup_stale()’ is abstract and must be implemented by a subclass
- class FileTicketQueue(
- queue_dir: str,
- stale_timeout: float | None = None,
Bases:
BaseTicketQueueFile-system backed ticket queue.
Tickets are assigned using a small
seqfile protected by an exclusive lock (fcntlon POSIX,msvcrton Windows). Each waiter creates a ticket file named{ticket:020d}.{pid}.{uuid}in the queue directory. The head of the sorted directory listing is considered the current owner.>>> # Basic filesystem queue behaviour and cleanup >>> import tempfile, os, time >>> tmp = tempfile.mkdtemp() >>> qd = tmp + "/q" >>> q = FileTicketQueue(qd, stale_timeout=0.01) >>> t1, m1 = q.register() >>> t2, m2 = q.register() >>> q.is_head(t1) True >>> q.remove(m1) >>> q.is_head(t2) True >>> # Make the remaining ticket appear stale and cleanup >>> p = os.path.join(qd, m2) >>> os.utime(p, (0, 0)) >>> q.cleanup_stale() >>> q.is_empty() True >>> q.maybe_cleanup() >>> os.path.exists(qd) False
- class RedisTicketQueue(
- name: str,
- client: redis.Redis | None = None,
- stale_timeout: float | None = None,
Bases:
BaseTicketQueueRedis-backed ticket queue using INCR + ZADD.
Member format:
{ticket}:{token}:{ts_ms}wherets_msis the insertion timestamp in milliseconds. The ZSET score is the ticket number which provides ordering. This class performs stale head cleanup based on the provided stale timeout.>>> # Redis queue examples; run only on non-Windows environments >>> def _redis_ticket_queue_doctest(): ... try: ... import time, redis ... client = redis.Redis() ... client.ping() ... except Exception: ... return print("True") ... ... name = "doctest:rq" ... # Ensure clean start ... _ = client.delete(f"{name}:queue") ... _ = client.delete(f"{name}:seq") ... q = RedisTicketQueue(name, client, stale_timeout=0.01) ... t1, m1 = q.register() ... t2, m2 = q.register() ... q.is_head(t1) ... True ... q.remove(m1) ... q.is_head(t2) ... True ... q.remove(m2) ... q.maybe_cleanup() ... print(client.exists(f"{name}:queue") == 0 and client.exists(f"{name}:seq") == 0) >>> import os >>> if os.name != 'nt': ... _redis_ticket_queue_doctest() ... else: ... print("True") True
re_entrant#
- class RLockFifo(
- name: str,
- timeout: float | None = None,
- blocking: bool = True,
- check_interval: float = 0.05,
- fifo: bool = True,
- fifo_stale_timeout: float | None = None,
Bases:
LockFifoA re-entrant cross-process lock backed by a file.
This lock is re-entrant for the same owner, identified by the tuple
(path, pid, thread_id). Repeated calls toacquire()by the same owner increment an internal counter, and only the finalrelease()releases the underlying file lock managed byLockFifo.- Key behaviour:
Owner identity: (path, pid, thread_id)
Reentrancy applies only within the same thread of the same process. Other threads or processes will block (or raise
LockTimeoutError) according to the lock’s timeout and blocking parameters.Implemented on top of
LockFifoand shares its constructor parameters and error semantics.
- Parameters:
name – Lock filename or path. If a simple name is given, it is created in the system temporary directory.
timeout – Seconds to wait for the lock.
Nonemeans block indefinitely.blocking – Whether to block until acquired (subject to
timeout).check_interval – Interval between lock attempts, in seconds.
fifo – Whether to enforce Fifo ordering (default: True).
fifo_stale_timeout – Seconds after which a ticket is considered stale; if
Nonethe lock’stimeoutvalue will be used.
- Raises:
LockTimeoutError – If the lock could not be acquired within the timeout (LockError & TimeoutError subclass)
LockError – On unexpected locking errors. (RunTimeError subclass)
>>> with RLockFifo("my.lock", timeout=5): ... # critical section ... pass
>>> lock = RLockFifo("my.lock") >>> lock.acquire() >>> lock.acquire() # re-entrant acquire by same thread/process >>> lock.release() >>> lock.release() # underlying lock released here
>>> # Reentrancy with Fifo enabled should not create multiple tickets >>> lock = RLockFifo("my_r.lock", fifo=True, timeout=1) >>> lock.acquire() >>> lock.acquire() >>> lock.release() >>> lock.release()
>>> # Cleanup behaviour: after closing a re-entrant lock the queue should be removed when empty >>> import tempfile, os >>> tmp = tempfile.mkdtemp() >>> p = tmp + "/rlock" >>> r = RLockFifo(p, fifo=True, timeout=1) >>> r.acquire(); r.acquire(); r.release(); r.release(); r.close() >>> os.path.exists(p + ".queue") False
- owners: ClassVar[dict[tuple[str, int, int], int]] = {}[source]#
Mapping of owner keys to re-entrant acquisition counts.
- acquire(
- timeout: float | None = None,
- blocking: bool | None = None,
- check_interval: float | None = None,
Acquire the lock with re-entrancy for the same owner.
If the current owner (same
self.key) already holds the lock, the internal counter is incremented and the underlying file lock is not re-acquired. Otherwise this delegates toLockFifo.acquire().
redis_fifo#
- class RedisLockFifo(
- name: str,
- redis_client: redis.Redis | None = None,
- timeout: float | None = None,
- blocking: bool = True,
- check_interval: float = 0.05,
- fifo: bool = True,
- fifo_stale_timeout: float | None = None,
Bases:
AbstractContextManager[RedisLockFifo]A Redis-backed inter-process lock (requires
redis).This lock provides optional Fifo fairness (enabled by default) and is implemented using atomic Redis primitives. Acquisition of the underlying lock uses an owner token and
SET NX(with optional PX expiry when a timeout/TTL is specified). When Fifo is enabled the implementation uses a small ticket queue usingINCR+ZADDand only the queue head attempts toSET NX. Release uses an atomic Lua script to ensure only the token owner can delete the lock key.Notes
The lock stores a locally-generated random token; releasing without the correct token has no effect on the remote key.
When Fifo is enabled, queue entries are removed when the client acquires the lock; stale queue entries (from crashed clients) are removed lazily when their age exceeds
fifo_stale_timeout(defaults totimeoutifNone).This class raises
ImportErrorif theredispackage is not installed and raisesLockTimeoutError/LockErrorfor runtime acquisition errors.
- Parameters:
name – Redis key name used for the lock.
redis_client – Optional Redis client. A client is created lazily if not provided.
timeout – Maximum time to wait for the lock in seconds, and the lock TTL of
SET PXwhen provided.Noneblocks indefinitely, without automatic expiry.blocking – Whether to block until acquired (subject to
timeout).check_interval – Poll interval while waiting for the lock, in seconds.
fifo – Whether to enforce Fifo ordering using a ZSET queue (default: True).
fifo_stale_timeout – Seconds after which a queue entry is considered stale, the lock’s
timeoutwhenNone. When both areNone, no stale cleanup is performed.
- Raises:
ImportError – If the
redispackage is not installed.LockTimeoutError – If the lock cannot be acquired within
timeout.LockError – On unexpected redis errors.
>>> # Redis-backed examples; run only on non-Windows environments >>> def _redis_doctest(): ... try: ... import redis, time ... client = redis.Redis() ... client.ping() ... except redis.exceptions.ConnectionError: ... return print("acquired\nTrue\nTrue") ... ... # Simple usage (assumes redis is available in the test environment) ... with RedisLockFifo('test:lock', timeout=1): ... pass ... ... # Non-Fifo usage example ... with RedisLockFifo('test:lock', fifo=False, timeout=1): ... pass ... ... # Fifo stale-ticket behaviour (requires a local redis server) ... # Inject a stale head entry ... name = 'doctest:lock:stale' ... _ = client.delete(f"{name}:queue") ... _ = client.delete(f"{name}:seq") ... _ = client.delete(name) ... old_ts = int((time.time() - 10) * 1000) ... _ = client.zadd(f"{name}:queue", {f"1:stale:{old_ts}": 1}) ... # Now acquire with small stale timeout which should remove head then succeed ... with RedisLockFifo(name, fifo=True, fifo_stale_timeout=0.01, timeout=1): ... print('acquired') ... _ = client.delete(f"{name}:queue") ... _ = client.delete(f"{name}:seq") ... _ = client.delete(name) ... # After using the lock, the queue keys should be removed when empty ... with RedisLockFifo(name, timeout=1): ... pass ... print(client.exists(f"{name}:queue") == 0 and client.exists(f"{name}:seq") == 0) ... ... # Non-Fifo acquisition should not create queue keys ... name2 = 'doctest:lock:nonfifo' ... _ = client.delete(f"{name2}:queue"); _ = client.delete(f"{name2}:seq") ... with RedisLockFifo(name2, fifo=False, timeout=1): ... pass ... print(client.exists(f"{name2}:queue") == 0 and client.exists(f"{name2}:seq") == 0) ... >>> import os >>> if os.name != 'nt': ... _redis_doctest() ... else: ... print("acquired\nTrue\nTrue") acquired True True
- RELEASE_SCRIPT: str = "\n if redis.call('get', KEYS[1]) == ARGV[1] then\n return redis.call('del', KEYS[1])\n else\n return 0\n end\n "[source]#
- acquire(
- timeout: float | None = None,
- blocking: bool | None = None,
- check_interval: float | None = None,
Acquire the Redis lock.
When Fifo is enabled (default), this function obtains a ticket via INCR and registers it in a ZSET. The client waits until its ticket is the head of the queue and then attempts to SET NX the lock key.