Overview:
- When a variable is created in thread local storage every thread will have its own copy which it can update.
- Thread local storage is not automatic variables.
- They are valid for the lifetime of the thread.
- They need not be locked for synchronization unless shared among threads.
- In Python, the class threading.local incorporates the concept of Thread local storage.
- A thread local variable can be added by instantiating a threading.local object and adding attributes to it. Each attribute added to the threading.local object is a thread local variable.
Example:
# Example Python program that uses thread local storage # Final sum # Calculates rolling sum and update the global sum # Create locks # Create threads that compute individual rolling sums t1.start() t1.join() |
Output:
Final sum after adding up numbers from each thread:32 |