In this case, you can just come up with an execution where MySingletonNTSafe
does the wrong thing in a multi-threaded environment. Here's one:
- Thread 1 calls
MySingtonNTSafe()
. It sees thatMySingletonNTSafe._instance is None
, then gets interrupted. - Thread 2 calls
MySingletonNTSafe()
. It sees thatMySingletonNTSafe._instance
is stillNone
, creates an instance, assigns it to_instance
, and returns it. - Thread 1 resumes execution. It creates an instance, assigns it to
_instance
, and returns it.
At this point, we have two instances, and the class has failed. It is not threadsafe.