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?
Double-checked locking is a common pattern for lazy initialization of a field accessed by multiple threads.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With