Using a global dictionary with threads in Python

后端 未结 5 775
野性不改
野性不改 2020-11-29 21:55

Is accessing/changing dictionary values thread-safe?

I have a global dictionary foo and multiple threads with ids id1, id2, ..

5条回答
  •  独厮守ぢ
    2020-11-29 22:05

    Since I needed something similar, I landed here. I sum up your answers in this short snippet :

    #!/usr/bin/env python3
    
    import threading
    
    class ThreadSafeDict(dict) :
        def __init__(self, * p_arg, ** n_arg) :
            dict.__init__(self, * p_arg, ** n_arg)
            self._lock = threading.Lock()
    
        def __enter__(self) :
            self._lock.acquire()
            return self
    
        def __exit__(self, type, value, traceback) :
            self._lock.release()
    
    if __name__ == '__main__' :
    
        u = ThreadSafeDict()
        with u as m :
            m[1] = 'foo'
        print(u)
    

    as such, you can use the with construct to hold the lock while fiddling in your dict()

提交回复
热议问题