Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Static Thread Variable

I have a number of threads in my software that all do the same thing, but each thread operates from a different "perspective." I have a "StateModel" object that is used throughout the thread and the objects within the thread, but StateModel needs to be calculated differently for each thread.

I don't like the idea of passing the StateModel object around to all of the functions that need it. Normally, I would create a module variable and all of the objects throughout the program could reference the same data from the module variable. But, is there a way to have this concept of a static module variable that is different and independent for each thread? A kind of static Thread variable?

Thanks.

like image 779
Crbreingan Avatar asked Sep 15 '25 06:09

Crbreingan


1 Answers

This is implemented in threading.local.

I tend to dislike mostly-quoting-the-docs answers, but... well, time and place for everything.

A class that represents thread-local data. Thread-local data are data whose values are thread specific. To manage thread-local data, just create an instance of local (or a subclass) and store attributes on it:

mydata = threading.local() 
mydata.x = 1 

The instance’s values will be different for separate threads.

For more details and extensive examples, see the documentation string of the _threading_local module.

Notably you can just have your class extend threading.local, and suddenly your class has thread-local behavior.

like image 194
roippi Avatar answered Sep 17 '25 20:09

roippi