简体   繁体   中英

Python locks that go away when process dies

Is there any locking interface for Python that automatically breaks the lock when the process dies? I was under the impression that sysv ipc allows for that, but I'm still trying to figure out the details.

What I expect from the interface:

  • lock / release functions
  • working between different processes on Linux
  • automatic unlock when the process holding the lock dies
  • forced lock breaking on timeout (not necessary)

You could apply locks to a file using fcntl.lockf or fcntl.flock . That seems to meet all your criteria. Or do you need something that doesn't require a system call every time you want to lock or unlock?

I usually use a try ... finally block to release a lock. eg

try:
    #do stuff
except Exception:
    pass
finally:
    #release lock

You could try the Lock objects in the built in multiprocessing package. I'm not sure whether the lock will automatically unlock when a process is garbage collected, but you could always subclass multiprocessing.Process like this:

class MyProc(multiprocessing.Process):
    def __init__(self):
        self.ipc_lock = multiprocessing.Lock()
        # ...
        return
    def __del__(self):
        self.ipc_lock.release()
        return

if you need to unlock if an exception is fired then put that in the (overridden) run method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM