Click here to Skip to main content
15,882,055 members
Articles / Programming Languages / C++
Tip/Trick

Terminate a hanging thread

Rate me:
Please Sign up or sign in to vote.
4.94/5 (9 votes)
16 Jan 2012CPOL 47K   9   4
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:


C++
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.


C++
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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Since you've suggested that, I started a blog off and have p... Pin
nicklowe5-Jan-12 6:36
nicklowe5-Jan-12 6:36 
GeneralReason for my vote of 4 Nearly correct, but needs to suspend... Pin
nicklowe4-Jan-12 14:31
nicklowe4-Jan-12 14:31 
GeneralRe: Thanks for your comment and vote. Yes, you are right, but in... Pin
trotwa5-Jan-12 2:54
trotwa5-Jan-12 2:54 
GeneralReason for my vote of 5 I've never tried this or heard of Rt... Pin
Albert Holguin2-Dec-11 7:52
professionalAlbert Holguin2-Dec-11 7:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.