🔒 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 of LockFifo.

  • 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)
Terminal output of the example, workers taking the lock one at a time

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,
)[source]#

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. None means 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 None the lock’s timeout value 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
path: str[source]#

The lock file path.

timeout: float | None[source]#

Maximum time to wait for the lock, in seconds. None means wait indefinitely.

blocking: bool[source]#

Whether to block until the lock is acquired (subject to timeout).

check_interval: float[source]#

Interval between lock acquisition attempts, in seconds.

file: IO[bytes] | None[source]#

The underlying file object.

fd: int | None[source]#

The underlying file descriptor.

is_locked: bool[source]#

Whether the lock is currently held.

member: str | None[source]#

The name of our ticket file in the queue directory when using Fifo.

fifo: bool[source]#

Whether Fifo ordering is enabled (default True).

fifo_stale_timeout: float | None[source]#

Seconds to consider a ticket stale and eligible for cleanup. If None, the lock’s timeout value will be used; if that is also None, no stale cleanup will be performed.

queue_dir: str[source]#

Directory used to store queue metadata and ticket files.

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,
) → None[source]#

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,
) → None[source]#

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.

release() → None[source]#

Release the lock.

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: object

Base 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

is_empty() → bool[source]#

Return True if the queue currently has no waiting members.

Implementations should consider the concrete storage details (e.g. on filesystem the “seq” file is not considered a queue member).

maybe_cleanup() → None[source]#

Attempt to remove any on-disk or remote artifacts when the queue is empty.

This should be a best-effort no-op if other clients are concurrently active. Implementations should handle errors internally and not raise.

class FileTicketQueue(
queue_dir: str,
stale_timeout: float | None = None,
)[source]#

Bases: BaseTicketQueue

File-system backed ticket queue.

Tickets are assigned using a small seq file protected by an exclusive lock (fcntl on POSIX, msvcrt on 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
cleanup_stale() → None[source]#

Remove stale head ticket if its mtime exceeds the stale timeout.

is_empty() → bool[source]#

Return True if the queue directory contains no ticket files.

The sequence file seq is ignored when determining emptiness.

maybe_cleanup() → None[source]#

Try to remove sequence file and queue dir if the queue is empty.

This is a best-effort operation: if other clients are active or a race occurs, the function simply returns without raising.

class RedisTicketQueue(
name: str,
client: redis.Redis | None = None,
stale_timeout: float | None = None,
)[source]#

Bases: BaseTicketQueue

Redis-backed ticket queue using INCR + ZADD.

Member format: {ticket}:{token}:{ts_ms} where ts_ms is 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
maybe_cleanup() → None[source]#

Attempt to remove Redis keys used by the queue when it is empty.

This is best effort: if concurrent clients are active the operation may be a no-op.

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,
)[source]#

Bases: LockFifo

A 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 to acquire() by the same owner increment an internal counter, and only the final release() releases the underlying file lock managed by LockFifo.

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 LockFifo and 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. None means 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 None the lock’s timeout value 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,
) → None[source]#

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 to LockFifo.acquire().

release() → None[source]#

Release the lock for this owner.

Decrements the re-entrant counter for the current owner and only when the counter reaches zero the underlying LockFifo is released.

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,
)[source]#

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 using INCR + ZADD and only the queue head attempts to SET 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 to timeout if None).

  • This class raises ImportError if the redis package is not installed and raises LockTimeoutError / LockError for 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 PX when provided. None blocks 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 timeout when None. When both are None, no stale cleanup is performed.

Raises:
  • ImportError – If the redis package 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]#
ensure_client() → redis.Redis[source]#

Ensure a redis.Redis client is available (lazy creation).

acquire(
timeout: float | None = None,
blocking: bool | None = None,
check_interval: float | None = None,
) → None[source]#

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.

release() → None[source]#

Release the lock if currently owned by this instance.

Uses an atomic Lua script to check that the stored token matches the key value and deletes it only when owned. Additionally removes any lingering queue entry for this client.

shared#

exception LockError[source]#

Bases: RuntimeError

Base lock error.

exception LockTimeoutError[source]#

Bases: TimeoutError, LockError

Raised when a lock could not be acquired within timeout seconds.

resolve_path(path: str) → str[source]#

Resolve a lock file path, placing it in the system temporary directory if only a name is given.

>>> import os, tempfile
>>> p = resolve_path('foo.lock')
>>> os.path.basename(p) == 'foo.lock'
True
resolve_acquire_defaults(
blocking_arg: bool | None,
timeout_arg: float | None,
check_interval_arg: float | None,
default_blocking: bool,
default_timeout: float | None,
default_check_interval: float,
) → tuple[bool, float | None, float, float | None][source]#

Resolve acquire() parameter defaults and compute the deadline.

Returns:

(blocking, timeout, check_interval, deadline)

wait_or_raise(
blocking: bool,
deadline: float | None,
check_interval: float,
name: str,
) → None[source]#

Sleep one check interval before the next attempt on a busy lock, or raise when waiting is not allowed.

Parameters:
  • deadline – time.monotonic() value past which waiting stops, None to wait forever.

  • name – Lock name or path the timeout message reports.

Raises:

LockTimeoutError – If blocking is False or deadline has passed.

>>> wait_or_raise(False, None, 0.0, "foo.lock")
Traceback (most recent call last):
    ...
stouputils.lock.shared.LockTimeoutError: Lock is already held and blocking is False
>>> wait_or_raise(True, 0.0, 0.0, "foo.lock")
Traceback (most recent call last):
    ...
stouputils.lock.shared.LockTimeoutError: Timeout while waiting for lock 'foo.lock'