Thread Local Storage In Python

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

 

import threading

 

userName = threading.local()

 

def SessionThread(userName_in):

    userName.val = userName_in

    print(userName.val)   

   

Session1 = threading.Thread(target=SessionThread("User1"))

Session2 = threading.Thread(target=SessionThread("User2"))

 

# start the session threads

Session1.start()

Session2.start()

 

# wait till the session threads are complete

Session1.join()

Session2.join()


Copyright 2023 © pythontic.com