test.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import sys, time, threading, thread, os, traceback, threadframe, pprint
  2. # daemon thread that spouts Monty Pythonesque nonsense
  3. class T(threading.Thread):
  4. def run(self):
  5. while 1:
  6. time.sleep(1)
  7. print '[%d] Spam spam spam spam. Lovely spam! Wonderful spam!' % ( thread.get_ident(), )
  8. # thread that cause a deliberate deadlock with itself
  9. U_lock = threading.Lock()
  10. class U(threading.Thread):
  11. def run(self):
  12. U_lock.acquire()
  13. U_lock.acquire()
  14. # thread that will exit after the thread frames are extracted but before
  15. # they are printed
  16. V_event = threading.Event()
  17. class V(threading.Thread):
  18. def run(self):
  19. V_event.clear()
  20. V_event.wait()
  21. print 'ident of main thread is: %d' % (thread.get_ident(),)
  22. print
  23. print 'launching daemon thread...',
  24. T().start()
  25. print 'done'
  26. print 'launching self-deadlocking thread...',
  27. U().start()
  28. print 'done'
  29. print 'launching thread that will die before the end...',
  30. v = V()
  31. v.start()
  32. print 'done'
  33. time.sleep(5)
  34. # Python 2.2 does not support threadframe.dict()
  35. if sys.hexversion < 0x02030000:
  36. frames = threadframe.threadframe()
  37. else:
  38. frames = threadframe.dict()
  39. # signal the thread V to die, then wait for it to oblige
  40. V_event.set()
  41. v.join()
  42. if sys.hexversion < 0x02030000:
  43. for frame in frames:
  44. print '-' * 72
  45. print 'frame ref count = %d' % sys.getrefcount(frame)
  46. traceback.print_stack(frame)
  47. else:
  48. for thread_id, frame in frames.iteritems():
  49. print '-' * 72
  50. print '[%s] %d' % (thread_id, sys.getrefcount(frame))
  51. traceback.print_stack(frame)
  52. os._exit(0)