stouputils.lock package#

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

Submodules#