Is there any easy way to have a system-wide mutex in Python on Linux? By \"system-wide\", I mean the mutex will be used by a group of Python processes; this is in c
My answer overlaps with the other answers, but just to add something people can copy-paste, I often do something like this.
class Locker:
def __enter__ (self):
self.fp = open("./lockfile.lck")
fcntl.flock(self.fp.fileno(), fcntl.LOCK_EX)
def __exit__ (self, _type, value, tb):
fcntl.flock(self.fp.fileno(), fcntl.LOCK_UN)
self.fp.close()
And then use it as:
print("waiting for lock")
with Locker():
print("obtained lock")
time.sleep(5.0)
To test, do touch lockfile.lck
then run the above code in two or more different terminals (from the same directory).