Python shelve module question

后端 未结 3 2042
忘了有多久
忘了有多久 2020-12-17 01:48

Does the Python shelve module have any protection built in to make sure two processes aren\'t writing to a file at the same time?

3条回答
  •  囚心锁ツ
    2020-12-17 02:23

    I've implemented Ivo's approach as a context manager, for anyone interested:

    from contextlib import contextmanager, closing
    from fcntl import flock, LOCK_SH, LOCK_EX, LOCK_UN
    import shelve
    
    @contextmanager
    def locking(lock_path, lock_mode):
        with open(lock_path, 'w') as lock:
            flock(lock.fileno(), lock_mode) # block until lock is acquired
            try:
                yield
            finally:
                flock(lock.fileno(), LOCK_UN) # release
    
    class DBManager(object):
        def __init__(self, db_path):
            self.db_path = db_path
    
        def read(self):
            with locking("%s.lock" % self.db_path, LOCK_SH):
                with closing(shelve.open(self.db_path, "c", 2)) as db:
                    return dict(db)
    
        def cas(self, old_db, new_db):
            with locking("%s.lock" % self.db_path, LOCK_EX):
                with closing(shelve.open(self.db_path, "c", 2)) as db:
                    if old_db != dict(db):
                        return False
                    db.clear()
                    db.update(new_db)
                    return True
    

提交回复
热议问题