Thursday, 17 December 2015

Python Thread local data

In python, we can define values specific to a thread. Create an instance of ‘threading.local()’ and store attributes in it.


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  mydata = threading.local()
  mydata.threadName = threading.current_thread().getName()
  mydata.threadId=threading.get_ident()
  time.sleep(1)
  print(mydata.threadName, mydata.threadId)
  
thread1 = MyThread(name="Thread_1")
thread2 = MyThread(name="Thread_2")
thread3 = MyThread(name="Thread_3")

thread1.start()
thread2.start()
thread3.start()

$ python3 MyThread.py 
Thread_1 4318040064
Thread_3 4339023872
Thread_2 4333768704



Previous                                                 Next                                                 Home

No comments:

Post a Comment