How to lock a critical section in Django?

前端 未结 6 1487
礼貌的吻别
礼貌的吻别 2020-12-02 14:49

I can\'t find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production

6条回答
  •  悲&欢浪女
    2020-12-02 15:18

    I ended up going with a solution I made myself involving file locking. If anyone here ends up using it remember that advisory locks and NFS don't mix well, so keep it local. Also, this is a blocking lock, if you want to mess around with loops and constantly checking back then there is instructions in the code.

    import os
    import fcntl
    
    class DjangoLock:
    
        def __init__(self, filename):
            self.filename = filename
            # This will create it if it does not exist already
            self.handle = open(filename, 'w')
    
        # flock() is a blocking call unless it is bitwise ORed with LOCK_NB to avoid blocking 
        # on lock acquisition.  This blocking is what I use to provide atomicity across forked
        # Django processes since native python locks and semaphores only work at the thread level
        def acquire(self):
            fcntl.flock(self.handle, fcntl.LOCK_EX)
    
        def release(self):
            fcntl.flock(self.handle, fcntl.LOCK_UN)
    
        def __del__(self):
            self.handle.close()
    
    Usage:
    
    lock = DJangoLock('/tmp/djangolock.tmp')
    lock.acquire()
    try:
        pass
    finally:
        lock.release()
    

提交回复
热议问题