title: Using win32com with multithreading
body: <p>I am working on a web app with CherryPy that needs to access a few applications via COM. </p>
  
  <p>Right now I create a new instance of the application with each request, which means each request waits 3 seconds for the application to start and 0.01 for the actual job.</p>
  
  <p>I would like to start each COM application once and keep it alive and reuse it for a few seconds on the following requests because most of the time it is used by a burst of 5-10 ajax requests, then nothing for hours.</p>
  
  <p>Is it possible to share a COM abject across all the threads of a CherryPy application?</p>
  
  <p>Here is the summary of a few experiments that show how it is working now on each request and how it does not work across threads.</p>
  
  <p>The following code successfully starts and stops Excel:</p>
  
  <pre><code>&gt;&gt;&gt; import pythoncom, win32com.client
  &gt;&gt;&gt; def start():
      global xl
      xl = win32com.client.Dispatch('Excel.Application')
  
  &gt;&gt;&gt; def stop():
      global xl
      xl.quit()
      xl = None
  
  &gt;&gt;&gt; start()
  &gt;&gt;&gt; stop()
  </code></pre>
  
  <p>But the following code starts Excel and closes it after 3 seconds.</p>
  
  <pre><code>&gt;&gt;&gt; import pythoncom, win32com.client, threading, time
  &gt;&gt;&gt; def start():
      global xl
      pythoncom.CoInitialize()
      xl = win32com.client.Dispatch('Excel.Application')
      time.sleep(3)
  
  &gt;&gt;&gt; threading.Thread(target=start).start()
  </code></pre>
  
  <p>I added the call to <code>CoInitialize()</code> otherwise the <code>xl</code> object would not work (see <a href="https://stackoverflow.com/questions/26745617/win32com-client-dispatch-cherrypy-coinitialize-has-not-been-called/26753031#26753031">this post</a>).</p>
  
  <p>And I added the 3 second pause, so I could see on the task manager that the EXCEL.EXE process starts and is alive for 3 seconds.</p>
  
  <p>Why does it die after the thread that started it ends?</p>
  
  <p>I checked the documentation of <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms678543(v=vs.85).aspx" rel="noreferrer"><code>CoInitialize()</code></a>, but I couldn't understand if it is possible to get it to work in multithreaded environment.</p>