0

Double check lock is a classic multi-threading issue discussed in many languages.

What I can find a discussion on Python is here: Is double-checked locking thread-safe in Python?

My question is: is below double check lock correct in Python3?

# Objects shared by threads:
obj = None
initialized:bool = False
lock_for_obj = threading.Lock()
 
def get_obj():
   """Function called concurrently by threads."""
    if not initialized:
         with lock_for_obj:
                if not initialized:
                    obj = factory()  # Never returns `None`
                    initialized = True

    return obj

In my opinion, if Python3 run statements line by line, then above double check lock is correct, since value assignment is atomic in Python3.

But if Python3 had some optimization on execution order, then the double check lock would fail.

I failed to Google an answer for this question, so I have to add a new question here.

If the above codes are wrong, is there a correct way to write a double check lock in Python?

Yongyi
  • 187
  • 11

0 Answers0