What is Thread Local Storage?
Thread Local Storage is a means where variables declared as thread local are made specific to thread instances.
Use cases of Thread Local Storage include -
- The famous error variable errno in C, declared global without thread synchronization is prone to overwrites in multithreaded environments
- Need of Thread specific counters
- To maintain contexts required by a complex application which could be on a per user or per session or per transaction basis
How Thread Local Storage is supported in Python:
The threading module in python provides the 'local' class for TLS - Thread Local Storage purposes.
The variable that needs to be made thread local is declared as an attributed of a local() instance and this attribute is accessed later.
Example of Thread Local Storage in Python:
# Thread Local Storage: Example Python Program
userName = threading.local()
userName.val = userName_in
Session1 = threading.Thread(target=SessionThread("User1"))
Session2 = threading.Thread(target=SessionThread("User2"))
# start the session threads
# wait till the session threads are complete