"""threadingSample.py shows how threading works BUG: if a KeyboardInterrupt is raised during the "while" loop, (after the main thread is done with countUp) then control is never returned to a Windows(r) console. """ import threading import random def countUp(index,timer): global result, earlyExit name = threading.currentThread().getName() for i in range(1,101): if earlyExit.isSet(): print 'earlyExit %s' % name break result[index] = i wait = random.random() * timer print "count=%3d wait=%4.2f thread= %s\n" %(result[index], wait, name), earlyExit.wait(wait) result = [None,None,None] earlyExit = threading.Event() T1 = threading.Thread(target=countUp,name='a',args=(1,2)) T2 = threading.Thread(target=countUp,name='b',args=(2,3)) T1.start() T2.start() try: countUp(0,1) while T1.isAlive() or T2.isAlive(): print 'Result = %s **Hit now to show the bug.**'%result T1.join(5) if not T1.isAlive(): print '*****T1 is done' T2.join(5) if not T2.isAlive(): print 'T2 is also done' except KeyboardInterrupt: print 'KeyboardInterrupt' earlyExit.set() print 'All done.'