Python: thread-safe implementation of a singleton
Boris HUISGEN March 23, 2019
Sometimes the singleton design pattern is required to limit resources usage like the number of connections to a database or an external service.
In other languages this design pattern could be difficult to write I mean specifically to satisfy the thread safety but for Python it’s not really the case. Here is my implementation.
Implementation
|
|
Test
To prove that it works let’s try with the python console:
$ python
>>> from code import MySingleton
>>> logging.basicConfig(level=logging.DEBUG, handlers=[logging.StreamHandler()])
>>> a = MySingleton()
DEBUG:MySingleton:using instance: <__main__.MySingleton object at 0x7f8bee80c550>
>>> b = MySingleton()
DEBUG:MySingleton:using instance: <__main__.MySingleton object at 0x7f8bee80c550>
>>> a.increment()
DEBUG:MySingleton:count = 1
>>> a.increment()
DEBUG:MySingleton:count = 2
>>> b.increment()
DEBUG:MySingleton:count = 3