User Tools

Site Tools


Python Thread Local Storage Example

With this tiny code snippet you can easily learn how to store thread specific data with the help of threading module of python programming language.

In this example, thread object initiated with an incrementor. Incrementor is used for assigning different values to thread_var variable and you can check it from the output. I initated thread_local variable in global scope but you can initate it within thread as well.
# -*- coding: utf-8 -*-
import threading
import time
import sys
thread_local = threading.local()
class MyThread(threading.Thread):
    def __init__(self, inc=1): = inc
        super(MyThread, self).__init__()
        self.local = thread_local
    def run(self):
        for x in range(0, 10 *,
            self.local.thread_var = str(x)
            sys.stdout.write(threading.current_thread().name +
                             " => thread_var=" + self.local.thread_var + "\n")
if __name__ == "__main__":
    a = MyThread(1)
    b = MyThread(10)
        while True:
            if not (a.is_alive() and b.is_alive()):
    except KeyboardInterrupt:

Output is:

Thread-1 => thread_var=0
Thread-2 => thread_var=0
Thread-1 => thread_var=1
Thread-2 => thread_var=10
Thread-2 => thread_var=20
Thread-1 => thread_var=2
Thread-2 => thread_var=30
Thread-1 => thread_var=3
Thread-2 => thread_var=40
Thread-1 => thread_var=4
Thread-1 => thread_var=5
Thread-2 => thread_var=50
Thread-2 => thread_var=60
Thread-1 => thread_var=6
Thread-2 => thread_var=70
Thread-1 => thread_var=7
Thread-2 => thread_var=80
Thread-1 => thread_var=8
Thread-2 => thread_var=90
Thread-1 => thread_var=9


Enter your comment. Wiki syntax is allowed:
python/misc/howto1.txt · Last modified: 2015/05/04 05:49 by ozan