testMarshal.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """Testing pasing object between multiple COM threads
  2. Uses standard COM marshalling to pass objects between threads. Even
  3. though Python generally seems to work when you just pass COM objects
  4. between threads, it shouldnt.
  5. This shows the "correct" way to do it.
  6. It shows that although we create new threads to use the Python.Interpreter,
  7. COM marshalls back all calls to that object to the main Python thread,
  8. which must be running a message loop (as this sample does).
  9. When this test is run in "free threaded" mode (at this stage, you must
  10. manually mark the COM objects as "ThreadingModel=Free", or run from a
  11. service which has marked itself as free-threaded), then no marshalling
  12. is done, and the Python.Interpreter object start doing the "expected" thing
  13. - ie, it reports being on the same thread as its caller!
  14. Python.exe needs a good way to mark itself as FreeThreaded - at the moment
  15. this is a pain in the but!
  16. """
  17. import threading, traceback
  18. import win32com.client
  19. import win32event, win32api
  20. import pythoncom
  21. import unittest
  22. from .testServers import InterpCase
  23. freeThreaded = 1
  24. class ThreadInterpCase(InterpCase):
  25. def _testInterpInThread(self, stopEvent, interp):
  26. try:
  27. self._doTestInThread(interp)
  28. finally:
  29. win32event.SetEvent(stopEvent)
  30. def _doTestInThread(self, interp):
  31. pythoncom.CoInitialize()
  32. myThread = win32api.GetCurrentThreadId()
  33. if freeThreaded:
  34. interp = pythoncom.CoGetInterfaceAndReleaseStream(interp, pythoncom.IID_IDispatch)
  35. interp = win32com.client.Dispatch(interp)
  36. interp.Exec("import win32api")
  37. #print "The test thread id is %d, Python.Interpreter's thread ID is %d" % (myThread, interp.Eval("win32api.GetCurrentThreadId()"))
  38. pythoncom.CoUninitialize()
  39. def BeginThreadsSimpleMarshal(self, numThreads):
  40. """Creates multiple threads using simple (but slower) marshalling.
  41. Single interpreter object, but a new stream is created per thread.
  42. Returns the handles the threads will set when complete.
  43. """
  44. interp = win32com.client.Dispatch("Python.Interpreter")
  45. events = []
  46. threads = []
  47. for i in range(numThreads):
  48. hEvent = win32event.CreateEvent(None, 0, 0, None)
  49. events.append(hEvent)
  50. interpStream = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_)
  51. t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interpStream))
  52. t.setDaemon(1) # so errors dont cause shutdown hang
  53. t.start()
  54. threads.append(t)
  55. interp = None
  56. return threads, events
  57. #
  58. # NOTE - this doesnt quite work - Im not even sure it should, but Greg reckons
  59. # you should be able to avoid the marshal per thread!
  60. # I think that refers to CoMarshalInterface though...
  61. def BeginThreadsFastMarshal(self, numThreads):
  62. """Creates multiple threads using fast (but complex) marshalling.
  63. The marshal stream is created once, and each thread uses the same stream
  64. Returns the handles the threads will set when complete.
  65. """
  66. interp = win32com.client.Dispatch("Python.Interpreter")
  67. if freeThreaded:
  68. interp = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_)
  69. events = []
  70. threads = []
  71. for i in range(numThreads):
  72. hEvent = win32event.CreateEvent(None, 0, 0, None)
  73. t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interp))
  74. t.setDaemon(1) # so errors dont cause shutdown hang
  75. t.start()
  76. events.append(hEvent)
  77. threads.append(t)
  78. return threads, events
  79. def _DoTestMarshal(self, fn, bCoWait = 0):
  80. #print "The main thread is %d" % (win32api.GetCurrentThreadId())
  81. threads, events = fn(2)
  82. numFinished = 0
  83. while 1:
  84. try:
  85. if bCoWait:
  86. rc = pythoncom.CoWaitForMultipleHandles(0, 2000, events)
  87. else:
  88. # Specifying "bWaitAll" here will wait for messages *and* all events
  89. # (which is pretty useless)
  90. rc = win32event.MsgWaitForMultipleObjects(events, 0, 2000, win32event.QS_ALLINPUT)
  91. if rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0+len(events):
  92. numFinished = numFinished + 1
  93. if numFinished >= len(events):
  94. break
  95. elif rc==win32event.WAIT_OBJECT_0 + len(events): # a message
  96. # This is critical - whole apartment model demo will hang.
  97. pythoncom.PumpWaitingMessages()
  98. else: # Timeout
  99. print("Waiting for thread to stop with interfaces=%d, gateways=%d" % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()))
  100. except KeyboardInterrupt:
  101. break
  102. for t in threads:
  103. t.join(2)
  104. self.failIf(t.is_alive(), "thread failed to stop!?")
  105. threads = None # threads hold references to args
  106. # Seems to be a leak here I can't locate :(
  107. #self.failUnlessEqual(pythoncom._GetInterfaceCount(), 0)
  108. #self.failUnlessEqual(pythoncom._GetGatewayCount(), 0)
  109. def testSimpleMarshal(self):
  110. self._DoTestMarshal(self.BeginThreadsSimpleMarshal)
  111. def testSimpleMarshalCoWait(self):
  112. self._DoTestMarshal(self.BeginThreadsSimpleMarshal, 1)
  113. # def testFastMarshal(self):
  114. # self._DoTestMarshal(self.BeginThreadsFastMarshal)
  115. if __name__=='__main__':
  116. unittest.main('testMarshal')