1

First off, let me start by saying that I understand all the perils of calling TerminateThread from outside a thread, instead of signaling the thread to quit by itself & wait for that to happen.

My question is, can I call TerminateThread right before the app quit. There's a 100% guarantee that the app will quit at that very moment. Do I risk to incur a memory leak in this case? Or anything that should prevent me from calling that API in this particular situation?

PS. I want to call it to let the application quit faster. It is too long to explain, but I need this app to quit ASAP upon a certain condition. (The app is a screensaver and should close as soon as a user moves the mouse.)

ahmd0
  • 16,633
  • 33
  • 137
  • 233
  • Obviously your application won't exit cleanly, but the operating system will reclaim all its resources when it terminates. If you're quitting anyway, why even bother with TerminateThread()? Just ExitProcess() and be done with it. – Luke Oct 31 '11 at 01:16
  • But, why is it bad in "won't exit cleanly"? Are you using sarcasm. Can you explain? I'm serious about it... – ahmd0 Oct 31 '11 at 01:35

1 Answers1

3

TerminateThread will probably just make things worse, since that will orphan critical sections (and if you're really unlucky, it will be the heap critical section or the loader critical section). If you really want to get out of dodge as fast as possible, just TerminateProcess yourself. Mind you, this bypasses all DLL_PROCESS_DETACH and global destructors, but you did say you wanted to exit as fast as possible.

EdChum
  • 376,765
  • 198
  • 813
  • 562
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • Thanks for suggestion. So if it that will bypass DLL_PROCESS_DETACH, how will that affect anything if my app is quitting and will be unloaded from memory anyway? Can you explain. – ahmd0 Oct 31 '11 at 02:26
  • 2
    When a process terminates, all its memory is discarded and all its handles are closed. That's the extent of it. If you left a shared memory block in an inconsistent state, then that's your problem. – Raymond Chen Oct 31 '11 at 02:46
  • OK. Again, I'm just trying to understand this and if calling TerminateProcess leads to my program somehow affecting the system, then I won't call it. Is that what you're saying? – ahmd0 Oct 31 '11 at 03:36
  • 1
    TerminateProcess won't affect the rest of the system, unless you've set it up so that it does (e.g. somehow modified shared resources that don't automatically get cleaned up by the OS). Also, if your process only has one thread then TerminateThread does exactly the same thing as TerminateProcess since the latter simply terminates all threads in the process anyway. – wj32 Oct 31 '11 at 08:35