thread2.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/python -u
  2. import string, sys, time
  3. import thread
  4. from threading import Thread, Lock
  5. import libxml2
  6. THREADS_COUNT = 15
  7. failed = 0
  8. class ErrorHandler:
  9. def __init__(self):
  10. self.errors = []
  11. self.lock = Lock()
  12. def handler(self,ctx,str):
  13. self.lock.acquire()
  14. self.errors.append(str)
  15. self.lock.release()
  16. def getLineNumbersDefault():
  17. old = libxml2.lineNumbersDefault(0)
  18. libxml2.lineNumbersDefault(old)
  19. return old
  20. def test(expectedLineNumbersDefault):
  21. time.sleep(1)
  22. global failed
  23. # check a per thread-global
  24. if expectedLineNumbersDefault != getLineNumbersDefault():
  25. failed = 1
  26. print "FAILED to obtain correct value for " \
  27. "lineNumbersDefault in thread %d" % thread.get_ident()
  28. # check ther global error handler
  29. # (which is NOT per-thread in the python bindings)
  30. try:
  31. doc = libxml2.parseFile("bad.xml")
  32. except:
  33. pass
  34. else:
  35. assert "failed"
  36. # global error handler
  37. eh = ErrorHandler()
  38. libxml2.registerErrorHandler(eh.handler,"")
  39. # set on the main thread only
  40. libxml2.lineNumbersDefault(1)
  41. test(1)
  42. ec = len(eh.errors)
  43. if ec == 0:
  44. print "FAILED: should have obtained errors"
  45. sys.exit(1)
  46. ts = []
  47. for i in range(THREADS_COUNT):
  48. # expect 0 for lineNumbersDefault because
  49. # the new value has been set on the main thread only
  50. ts.append(Thread(target=test,args=(0,)))
  51. for t in ts:
  52. t.start()
  53. for t in ts:
  54. t.join()
  55. if len(eh.errors) != ec+THREADS_COUNT*ec:
  56. print "FAILED: did not obtain the correct number of errors"
  57. sys.exit(1)
  58. # set lineNumbersDefault for future new threads
  59. libxml2.thrDefLineNumbersDefaultValue(1)
  60. ts = []
  61. for i in range(THREADS_COUNT):
  62. # expect 1 for lineNumbersDefault
  63. ts.append(Thread(target=test,args=(1,)))
  64. for t in ts:
  65. t.start()
  66. for t in ts:
  67. t.join()
  68. if len(eh.errors) != ec+THREADS_COUNT*ec*2:
  69. print "FAILED: did not obtain the correct number of errors"
  70. sys.exit(1)
  71. if failed:
  72. print "FAILED"
  73. sys.exit(1)
  74. # Memory debug specific
  75. libxml2.cleanupParser()
  76. if libxml2.debugMemory(1) == 0:
  77. print "OK"
  78. else:
  79. print "Memory leak %d bytes" % (libxml2.debugMemory(1))
  80. libxml2.dumpMemory()