Tuesday, 15 December 2015

Python: Set trace function for a thread

‘threading.settrace(func)’ sets a trace function for all threads started from the threading module.

Following post explain about trace function in detail.



MyThread.py
import threading
import time
import linecache

def traceit(frame, event, arg):
    if event == "line":
        lineno = frame.f_lineno
        line = linecache.getline("test.py", lineno)
        print("line", lineno, line)

    return traceit

class MyThread(threading.Thread):
 def run(self):
  print(threading.current_thread().getName()," with id ",threading.get_ident()," Started")
  print(threading.current_thread().getName()," with id ",threading.get_ident()," Finished")
  
threading.settrace(traceit)

thread1 = MyThread(name="Thread_1")
thread2 = MyThread(name="Thread_2")
thread3 = MyThread(name="Thread_3")

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

$ python3 MyThread.py 
line 15         line = linecache.getline("test.py", lineno)

line 1240 
line 1241 
line 1158 
line 1091 
line 1092 
Thread_1  with id  4318040064  Started
line 16         print("line", lineno, line)

line 1240 
line 1241 
line 1158 
line 1091 
line 1092 
Thread_1  with id  4318040064  Finished
line 15         line = linecache.getline("test.py", lineno)

line 15         line = linecache.getline("test.py", lineno)
line 1240 

line 1240 
line 1241 
line 1158 
line 1241 
line 1091 
line 1158 
line 1092 
Thread_2  with id  4333768704  Started
line 1091 
line 16         print("line", lineno, line)

line 1092 
line 1240 
Thread_3  with id  4350545920  Started
line 1241 
line 16         print("line", lineno, line)

line 1240 
line 1241 
line 1158 
line 1091 
line 1158 
line 1091 
line 1092 
line 1092 
Thread_3  with id  4350545920  Finished
Thread_2  with id  4333768704  Finished


Previous                                                 Next                                                 Home

No comments:

Post a Comment