Debugging Multi-Threaded Python Programs

Alan Green web.mail at lycos.com
Thu Aug 16 02:28:32 CEST 2001


I've been trying to demonstrate Python debuggers to a colleague. One
thing that everyone here is keen to see is debugging of multi-threaded
programs.

The program below is what I have been using to test - the idea is to
catch a the 'naughty' thread modifying a shared global value. So far,
I've only been able to set breakpoints on the program's main thread.
Breakpoints on other threads do not work.

A quick look at the Python source and libraries tells me that:

(a) Debuggers hook into the interpreter via sys.settrace().
sys.settrace() sets a trace function for _the current thread only_.

(b) pdb (the standard debugger module) and the IDLE debugger are both
based on the bdb module, which only call sys.settrace() on one thread.

I've also tried Komodo and PythonWin, with exactly the same results:
breakpoints only work on the main thread.

Has anyone out there had luck with interactively debugging
multi-threaded Python programs? On Windows? Is there an alternative to
implementing my own GUI debugger (which won't happen)?

Alan.


--- ThreadTest.py ---
from time import sleep, time
from random import randrange
import threading

NUM_THREADS = 5
SHARED_GLOBAL_VALUE = 10
END_TIME = 0

class Worker(threading.Thread):
    # Use the shared value
    def run(self):
        while int(time()) < END_TIME:
            sleep(randrange(5))
            print int(time()), "That value is:", SHARED_GLOBAL_VALUE

class Saboteur(threading.Thread):
    # Sabotage the shared value
    def run(self):
        sleep(15)
        global SHARED_GLOBAL_VALUE
        SHARED_GLOBAL_VALUE = 999  ### Breakpoint Here Does Not Work
###

END_TIME = int(time()) + 20
print "Will Finish at: ", END_TIME

for i in range(NUM_THREADS):  
    Worker().start()  ### Breakpoint Here Works ###
Saboteur().start()



More information about the Python-list mailing list