I'm using Python to write a multi-threaded application. In my application, one thread will update a reference variable periodically, and multiple threads will access that variable. To update the reference, the update thread will create a new local variable, then make it visible by pointing the global reference to the new one. Other threads will only access this shared reference once per request. The pseudo-code is as follows:
ALL_DATA = load_all_data()
lock = Lock()
# Thread 1
while 1:
sleep(500)
new_all_data = load_all_data()
with lock:
ALL_DATA = new_all_data
# Other theads
def predict(image_url: str):
with lock:
_data = ALL_DATA
# Using _data to process request
My question is do I need to use the lock as above when updating, and accessing the shared reference variable?