views:

37

answers:

1

I have a native Visual C++ NT service. When the service is started its thread calls CoInitialize() which attaches the thread to an STA - the service thread uses MSXML through COM interfaces.

When the service receives SERVICE_CONTROL_STOP it posts a message in the message queue, then later that message is retrieved and the OnStop() handler is invoked. The handler cleans up stuff and calls CoUnitialize(). Most of the time it works allright, but once in a while the latter call hangs. I can't reproduce this behavior stably.

I googled for a while and found the following likely explanations:

  1. failing to release all COM objects owned
  2. repeatedly calling CoInitializeEx()/CoUnitialize() for attaching to MTA
  3. failing to dispatch messaged in STA threads

The first one is unlikely - the code using MSXML is well tested and analyzed and it uses smart pointers to control objects lifetime, so leaking objects is really unlikely.

The second one doesn't look like the likely reason. I attach to STA and don't call those functions repeatedly.

The third one looks more or less likely. While the thread is processing the message it doesn't run the message loop anymore - it is inside the loop already. I suppose this might be the reason.

Is the latter a likely reason for this problem? What other reasons should I consider? How do I resolve this problem easily?

A: 

Don't do anything of consequence in the thread handling SCM messages, it's in a weird magical context - you must answer SCM's requests as fast as possible without taking any blocking action. Tell it you need additional time via STOP_PENDING, queue another thread to do the real cleanup, then immediately complete the SCM message.

As to the CoUninitialize, just attach WinDbg and dump all the threads - deadlocks are easy to diagnose (maybe not to fix!), you've got all of the parties to the crime right there in the stacks.

Paul Betts
I guess you understand that I don't like the idea of introducing a separate thread in the first place. Also I can't call `CoUninitialize()` on another thread - I have to call it on the thread that originally called `CoInitialize()`.
sharptooth
So don't call CoInitialize on the SCM thread.
Paul Betts
Yeap, I got your idea. Introducing a separate thread just for handling SCM requests will compilcate the program greatly. And the key is I don't even know if it will solve the problem in question.
sharptooth