pythonmultithreadinglanguage-lawyer

Is double-checked locking thread-safe in Python?


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?


Solution

  • Have a look at PEP 583 - Concurrency memory model for Python, which was withdrawn.

    I guess the reason it was withdrawn (though I can't find enough information on that) is since there are different implementations of Python, and it's difficult to enforce a standard like this on every one of them.

    Conclusion: this code might be safe when using CPython implementation on a single processor, or it might be safe to use it in general using Jython implementation, but there's no guarantee.