2

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?

Anh Duc Ng
  • 169
  • 1
  • 8
  • 1
    Does this answer your question? [Is Python variable assignment atomic?](https://stackoverflow.com/questions/2291069/is-python-variable-assignment-atomic) – Piotr Dobrogost Dec 09 '22 at 09:04
  • 3
    I would use the lock even if it was not strictly necessary. Two reasons: One, I write more code in other programming languages than I write in Python, and in most other programming languages, the lock would be necessary—call it a "style" thing. Reason two: it "future proofs" the code. There's a _reason_ why it's necessary in other programming languages but not in Python, and that reason is Python's Global Interpreter Lock (the GIL). Everybody wants the GIL to go away. And if they ever do decide to take it away, that lock might become necessary. – Solomon Slow Dec 09 '22 at 12:59

0 Answers0