Enforcing Singleton per Thread with Thread-Local Storage

Learn how to enforce the Singleton design pattern per thread in Python using thread-local storage to ensure each thread maintains its own Singleton instance.
Enforcing Singleton Per Thread in Python Using Thread-Local Storage
In this tutorial, we explore how to enforce the Singleton design pattern per thread in Python. This approach ensures that each thread maintains its own unique instance of a Singleton object, which is particularly useful in multi-threaded applications that require thread-specific data isolation.
Why Thread-Local Singleton?
Normally, the Singleton pattern restricts instantiation to a single object globally. However, in multi-threaded programs, there are scenarios where each thread needs its own Singleton instance, isolated from other threads. This prevents shared state conflicts and race conditions.
What is Thread-Local Storage?
Thread-local storage (TLS) allows data to be stored such that each thread has its own independent copy. In Python, this is achieved using threading.local
, which provides a way to manage thread-specific data without interference.
Implementing Singleton Per Thread
We will now implement a Singleton class where each thread gets its own instance:
import threading
class ThreadSingleton:
_thread_local = threading.local()
def __new__(cls, *args, **kwargs):
if not hasattr(cls._thread_local, \\"instance\\"):
cls._thread_local.instance = super(ThreadSingleton, cls).__new__(cls)
return cls._thread_local.instance
def __init__(self, value):
self.value = value
def worker(name, value):
singleton = ThreadSingleton(value)
print(f\\"Thread name: Singleton value = singleton.value\\")
thread1 = threading.Thread(target=worker, args=(\\"A\\", \\"Alpha\\"))
thread2 = threading.Thread(target=worker, args=(\\"B\\", \\"Beta\\"))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
In this code, each thread creates its own instance of ThreadSingleton
using threading.local
. The value
assigned in one thread does not affect the Singleton in another thread.
Output
When running the code, you will see each thread printing its unique Singleton value:
Thread A: Singleton value = Alpha
Thread B: Singleton value = Beta
This confirms that each thread has an isolated Singleton instance.
Conclusion
Thread-local Singleton is an elegant solution for thread-specific data in Python. By using threading.local
, we avoid race conditions and maintain clean isolation of state across threads, making our applications safer and more maintainable.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/enforcing-singleton-per-thread-with-thread-local-storage/?feed_id=13334&_unique_id=6899744716b55
Comments
Post a Comment