Sunday, 5 May 2019

Is double-checked locking safe in Python? When and when not?

The double-checked locking idiom is not reliable in some languages, and I want to know whether Python is one of them. More concretely, is the following code...

# Objects shared by threads:
obj = None
lock_for_obj = threading.Lock()

def get_obj():
    """Function called concurrently by threads."""
    if obj is None:
        with lock_for_obj:
            if obj is None:
                obj = factory()  # Never returns `None`
    return obj

...thread-safe in Python? Are there scenarios/implementations where it is/isn't? Why?



from Is double-checked locking safe in Python? When and when not?

No comments:

Post a Comment