在python(django)中,如何在更新全局字典数据结构时停止对其进行访问? [英] In python (django) how can I stop access to a global dictionary data structure when it's being updated?

查看:91
本文介绍了在python(django)中,如何在更新全局字典数据结构时停止对其进行访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,当更新全局字典数据结构时,我想通过其他请求来锁定对其的访问。我打算具有包装器功能来更新,访问和同步它。来自Java背景!有指针吗?

In django when updating a global dictionary data structure I want to lock access to it by different request. I am planning to have a wrapper function to update and access and synchronize it. Coming from Java background! Any pointers?

推荐答案

稍微扩展LockableDict示例,使其更加健壮,您可以使用真正的Lock:

Extending the LockableDict example somewhat, to make it a little more robust you can use the real Lock:

class LockableDict(dict):
    def __init__(self, *args, **kwargs):
        from threading import Lock
        self.lock = Lock()
        dict.__init__(self, *args, **kwargs)

    @property
    def locked(self):
        return self.lock.locked()

    def lock(self):
        self.lock.acquire()

    def unlock(self):
        self.lock.release()

# and then
my_dict = LockableDict({1:2, 3:4})
my_dict.lock()
# do modifications
my_dict.unlock()

这篇关于在python(django)中,如何在更新全局字典数据结构时停止对其进行访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆