System-wide mutex in Python on Linux

后端 未结 6 1384
终归单人心
终归单人心 2020-12-04 21:02

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

6条回答
  •  北海茫月
    2020-12-04 21:59

    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).

提交回复
热议问题