65.9K
CodeProject is changing. Read more.
Home

Terminate a hanging thread

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.94/5 (9 votes)

Nov 24, 2011

CPOL
viewsIcon

48247

How to avoid memory leak in WinXP, if you kill a thread

I wrote some code to display all open handles in the system. This is usually a device driver job, but I wrote a workaround for it... The problem was only that my thread was hanging occasionally in an undocumented API. ;)

It wasn't a problem to kill this thread and create another one, but in WinXP this generates a memory leak: The stack isn't freed via TerminateThread(). This doesn't happen in Vista and newer systems.

Therefore I used another undocumented API:

typedef	VOID (WINAPI *PRtlFreeUserThreadStack)(HANDLE hProcess, HANDLE hThread);
static PRtlFreeUserThreadStack RtlFreeUserThreadStack=NULL;

HMODULE NTLibrary = GetModuleHandleW(L"ntdll.dll");
RtlFreeUserThreadStack = (PRtlFreeUserThreadStack)GetProcAddress(NTLibrary, "RtlFreeUserThreadStack");

The nice thing is, that RtlFreeUserThreadStack() is only available in WinXP and older systems. Therefore the rule is: Use it, if it is available.

void KillThread(HANDLE threadHandle)
{
   //SetEvent(waitEvent);
   DWORD dwExitCode;
   GetExitCodeThread(threadHandle, &dwExitCode); // check again
   if(dwExitCode == STILL_ACTIVE)
   {
      if(RtlFreeUserThreadStack != NULL)
         RtlFreeUserThreadStack(GetCurrentProcess(), threadHandle);
      TerminateThread(threadHandle, 0); 
   }
   CloseHandle(threadHandle);
}