User Tools

Site Tools


Advertisements: AliExpress Hide Your IP Microsoft Products
python:misc:howto1

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.

example1.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import threading
import time
import sys
 
thread_local = threading.local()
 
 
class MyThread(threading.Thread):
 
    def __init__(self, inc=1):
        self.inc = inc
        super(MyThread, self).__init__()
        self.local = thread_local
 
    def run(self):
        for x in range(0, 10 * self.inc, self.inc):
            time.sleep(1)
            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)
    a.start()
 
    b = MyThread(10)
    b.start()
 
    try:
        while True:
            time.sleep(0.1)
            if not (a.is_alive() and b.is_alive()):
                break
    except KeyboardInterrupt:
        sys.stdout.write("Exited")

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

Discussion

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