【问题标题】:Is shelve in Python thread safe?Python线程中的搁置是否安全?
【发布时间】:2011-03-04 02:52:25
【问题描述】:

Python 中的 shelve 用于数据持久化线程安全吗?如果没有,有什么好的选择?

【问题讨论】:

    标签: python thread-safety shelve


    【解决方案1】:

    来自standard library documentation about the Shelve module, under the heading Restrictions

    搁置模块不支持 并发读/写访问 搁置的物品。 (多 同时读取访问是安全的。)

    我会假设它可能依赖于实现,在这种情况下,为了确定,我会得出结论,它肯定不是线程安全的。

    【讨论】:

    • 感谢您的评论。在文档的下一部分中,它说:“当一个程序有一个架子可供写入时,其他程序都不应该打开它来读取或写入。可以使用 Unix 文件锁定来解决这个问题,但这在 Unix 版本之间有所不同,并且需要了解所使用的数据库实现。” - 这表明搁置模块不是线程安全的,除非您实现自己的锁定机制。您是否有其他示例?
    【解决方案2】:

    替代品:ZODB

    http://www.zodb.org/

    【讨论】:

    • (from link) (ZODB...) 事务提供隔离 事务允许多个逻辑线程(线程或进程)访问数据库,数据库防止线程进行冲突更改。
    【解决方案3】:
    Threads = # amount of threads
    
    thread_moment = [False for _ in range(Threads)] 
    
    def job(x):  # x would be the index of the thread  
    
        lock.aquire()
    
        # open/edit/update/close your shelve file
    
        thread_moment[x] = True 
    
        lock.release()
    
        while True:
            if all(thread_moment) == True:
                thread_moment = [False for _ in range(threads)]
                break
            else:
                time.sleep(1)
    
        # carry on with your script
    

    【讨论】:

    • 问题是关于它是否安全......你的代码如何回答这个问题?
    猜你喜欢
    • 2023-03-22
    • 2012-08-21
    • 2014-10-10
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多