What is the correct way to implement a thread-safe singleton in Python using a lock?

Python Professional Hard

Python Professional — Hard

What is the correct way to implement a thread-safe singleton in Python using a lock?

Key points

  • Acquiring a lock in __new__ prevents multiple threads from creating multiple instances simultaneously.
  • Using a lock ensures that the singleton is thread-safe and avoids race conditions.
  • The lock is released after the instance is created, maintaining thread safety.

Ready to go further?

Related questions