testGIT.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 _thread, traceback
  18. import win32com.client
  19. import win32event, win32api
  20. import pythoncom
  21. def TestInterp(interp):
  22. if interp.Eval("1+1") != 2:
  23. raise ValueError("The interpreter returned the wrong result.")
  24. try:
  25. interp.Eval(1+1)
  26. raise ValueError("The interpreter did not raise an exception")
  27. except pythoncom.com_error as details:
  28. import winerror
  29. if details[0]!=winerror.DISP_E_TYPEMISMATCH:
  30. raise ValueError("The interpreter exception was not winerror.DISP_E_TYPEMISMATCH.")
  31. def TestInterpInThread(stopEvent, cookie):
  32. try:
  33. DoTestInterpInThread(cookie)
  34. finally:
  35. win32event.SetEvent(stopEvent)
  36. def CreateGIT():
  37. return pythoncom.CoCreateInstance(pythoncom.CLSID_StdGlobalInterfaceTable,
  38. None,
  39. pythoncom.CLSCTX_INPROC,
  40. pythoncom.IID_IGlobalInterfaceTable)
  41. def DoTestInterpInThread(cookie):
  42. try:
  43. pythoncom.CoInitialize()
  44. myThread = win32api.GetCurrentThreadId()
  45. GIT = CreateGIT()
  46. interp = GIT.GetInterfaceFromGlobal(cookie, pythoncom.IID_IDispatch)
  47. interp = win32com.client.Dispatch(interp)
  48. TestInterp(interp)
  49. interp.Exec("import win32api")
  50. print("The test thread id is %d, Python.Interpreter's thread ID is %d" % (myThread, interp.Eval("win32api.GetCurrentThreadId()")))
  51. interp = None
  52. pythoncom.CoUninitialize()
  53. except:
  54. traceback.print_exc()
  55. def BeginThreadsSimpleMarshal(numThreads, cookie):
  56. """Creates multiple threads using simple (but slower) marshalling.
  57. Single interpreter object, but a new stream is created per thread.
  58. Returns the handles the threads will set when complete.
  59. """
  60. ret = []
  61. for i in range(numThreads):
  62. hEvent = win32event.CreateEvent(None, 0, 0, None)
  63. _thread.start_new(TestInterpInThread, (hEvent, cookie))
  64. ret.append(hEvent)
  65. return ret
  66. def test(fn):
  67. print("The main thread is %d" % (win32api.GetCurrentThreadId()))
  68. GIT = CreateGIT()
  69. interp = win32com.client.Dispatch("Python.Interpreter")
  70. cookie = GIT.RegisterInterfaceInGlobal(interp._oleobj_, pythoncom.IID_IDispatch)
  71. events = fn(4, cookie)
  72. numFinished = 0
  73. while 1:
  74. try:
  75. rc = win32event.MsgWaitForMultipleObjects(events, 0, 2000, win32event.QS_ALLINPUT)
  76. if rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0+len(events):
  77. numFinished = numFinished + 1
  78. if numFinished >= len(events):
  79. break
  80. elif rc==win32event.WAIT_OBJECT_0 + len(events): # a message
  81. # This is critical - whole apartment model demo will hang.
  82. pythoncom.PumpWaitingMessages()
  83. else: # Timeout
  84. print("Waiting for thread to stop with interfaces=%d, gateways=%d" % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()))
  85. except KeyboardInterrupt:
  86. break
  87. GIT.RevokeInterfaceFromGlobal(cookie)
  88. del interp
  89. del GIT
  90. if __name__=='__main__':
  91. test(BeginThreadsSimpleMarshal)
  92. win32api.Sleep(500)
  93. # Doing CoUninit here stop Pythoncom.dll hanging when DLLMain shuts-down the process
  94. pythoncom.CoUninitialize()
  95. if pythoncom._GetInterfaceCount()!=0 or pythoncom._GetGatewayCount()!=0:
  96. print("Done with interfaces=%d, gateways=%d" % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()))
  97. else:
  98. print("Done.")