Python搁置模块问题

时间:2009-01-28 04:32:14

标签: python shelve

Python搁置模块是否内置了任何保护措施以确保两个进程不会同时写入文件?

3 个答案:

答案 0 :(得分:7)

shelve模块使用底层数据库包(例如dbm,gdbm或bsddb)。

restrictions pragraph说(我的重点):

  

搁置模块不支持对搁置对象的并发读/写访问。 (多个同时读取访问是安全的。)当程序打开一个架子进行写入时,没有其他程序可以打开它进行读写。 Unix文件锁定可用于解决此问题,但这在Unix版本中有所不同,需要了解所使用的数据库实现。

结论:它取决于操作系统和底层数据库。为了保持可移植性,不要建立在并发上。

答案 1 :(得分:2)

根据最佳答案,将多个作家留在货架上是不安全的。我制作货架更安全的方法是编写一个包装器,负责打开和访问货架元素。包装器代码如下所示:

def open(self, mode=READONLY):
    if mode is READWRITE:
        lockfilemode = "a" 
        lockmode = LOCK_EX
        shelve_mode = 'c'
    else:
        lockfilemode = "r"
        lockmode = LOCK_SH
        shelve_mode = 'r'
    self.lockfd = open(shelvefile+".lck", lockfilemode)
    fcntl.flock(self.lockfd.fileno(), lockmode | LOCK_NB)
    self.shelve = shelve.open(shelvefile, flag=shelve_mode, protocol=pickle.HIGHEST_PROTOCOL))
def close(self):
    self.shelve.close()
    fcntl.flock(self.lockfd.fileno(), LOCK_UN)
    lockfd.close()

答案 2 :(得分:2)

我已经为所有感兴趣的人实施了Ivo's approach作为上下文管理器:

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