Processes Locks: Inter-Processes Locks
Learn about inter-processes locks in Python.
We'll cover the following
As stated earlier, multiprocessing.Lock
only works for processes started from a single Python process. If your application is distributed across several Python processes, such as a daemon started independently, you need an interprocess lock mechanism.
Those locks are usually not portable across operating systems. POSIX, System V or even Windows all offer different interprocess communication mechanisms, and they are not compatible with one another. You may want to look in this direction if you are not afraid of making your software platform-dependent.
fasteners
The fasteners
module provides an excellent implementation of a generic solution based on file locks in Python.
Note: Locks implemented by
fasteners
are based on file-system locks. They are not specific to Python. Therefore you could also implement the same file-locking mechanism in another programming language in order to have cross-language locking.
Fasteners provides a lock class fasteners.InterProcessLock
that takes a file path as its first argument. This file path is going to be the identifier for this lock, and it can be used across multiple independent processes. This is why fasteners is helpful to lock access to resources across processes that were started independently.
To run the application below, press the Run button and run the command
python fasteners-lock.py
.
Get hands-on with 1400+ tech skills courses.