Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 450
Brian Rodriguez Avatar asked May 02 '19 17:05

Brian Rodriguez


People also ask

Is double-checked locking thread safe?

Double-checked locking is a common pattern for lazy initialization of a field accessed by multiple threads.

Why does double-checked locking not work?

Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment. Unfortunately, it will not work reliably in a platform independent way when implemented in Java, without additional synchronization.

What is double locking in thread?

In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock.

Why you need double-checked locking of singleton class?

This double check lock is only necessary if you are worried about many threads calling the singleton simultaneously, or the cost of obtaining a lock in general. Its purpose is to prevent unnecessary synchronization, thereby keeping your code fast in a multi-threaded environment.


1 Answers

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.

like image 174
Michael Spector Avatar answered Oct 31 '22 20:10

Michael Spector