How to add lock by id in python

Asked by At

There is a function to get the object by the key, the objects is stored in a dict, if key does not exist, then initialize the object according to the key, then put the key and object to the dict, and return the object , How to ensure in the python multi-thread environment The initialization operation is not repeated when it does not exist, and does not block access to other keys.

1 Answers

Syed Zubair Ahamed On

locks with similar to any other programming languages.

from threading import Lock, Thread
lock = Lock()
g = 0

def add_one(): 
   global g
   g += 1