Fasteners

0.20 · active · verified Sun Mar 29

Fasteners is a Python package that provides useful cross-platform synchronization primitives. It extends Python's standard library by offering inter-process exclusive locks, inter-process reader-writer locks, and thread-based reader-writer locks. The library aims to simplify concurrent programming across processes and threads. The current version is 0.20, with releases occurring periodically, often tied to Python version support updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `fasteners.interprocess_locked` as a decorator and `fasteners.InterProcessLock` as a context manager to ensure exclusive execution across processes using a file-based lock. If you run multiple instances of this script simultaneously, only one will execute the protected section at a time.

import time
import fasteners
import os

# For inter-process locks, a file path is required.
# Use a temporary file path for demonstration.
lock_file_path = os.path.join(os.getcwd(), 'my_app.lock')

@fasteners.interprocess_locked(lock_file_path)
def protected_function(worker_id):
    print(f"Worker {worker_id}: Acquired lock. Performing exclusive task...")
    time.sleep(2)  # Simulate work
    print(f"Worker {worker_id}: Released lock.")

if __name__ == "__main__":
    print(f"Attempting to run protected_function for worker 1...")
    protected_function(1)
    print(f"Attempting to run protected_function for worker 2...")
    protected_function(2)

    # Example with context manager for more control
    print("\n--- Using context manager ---")
    my_lock = fasteners.InterProcessLock(lock_file_path + '.ctx')
    with my_lock:
        print("Main process: Acquired lock via context manager.")
        time.sleep(1)
    print("Main process: Released lock via context manager.")
    
    # Clean up lock files (optional, as fasteners typically handles this on exit)
    if os.path.exists(lock_file_path):
        os.remove(lock_file_path)
    if os.path.exists(lock_file_path + '.ctx'):
        os.remove(lock_file_path + '.ctx')

view raw JSON →