User Tools

Site Tools


python:misc:howto1

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
python:misc:howto1 [2015/04/19 12:05]
ozan
python:misc:howto1 [2015/05/04 05:49] (current)
ozan
Line 1: Line 1:
 +===== 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.
 +
 +<file python 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"​)
 +
 +</​file>​
 +
 +Output is:
 +<​code>​
 +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
 +
 +</​code>​
 +{{tag>​python programming tutorial thread threading storage threading.local python_local_storage}}
 +~~DISCUSSION~~
python/misc/howto1.txt ยท Last modified: 2015/05/04 05:49 by ozan