Search code examples
pythonconcurrency

Why is it thread-safe to perform lazy initialization in python?


I just read this blog post about a recipe to lazily initialize an object property. I am a recovering java programmer and if this code was translated into java, it would be considered a race condition (double check locking). Why does it work in python ? I know there is a threading module in python. Are locks added surreptitiously by the interpreter to make this thread-safe?

How does canonical thread-safe initialisation look in Python?


Solution

    1. No, no locks are added automatically.
    2. That's why this code is not thread-safe.
    3. If it seems to work in a multi-threaded program without problems, it's probably due to the Global Interpreter Lock, which makes the hazard less likely to occur.