is it safe to use TerminateThread() that way?

Hello guys!

I read from https://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx

that
TerminateThread is a dangerous function that should only be used in the most extreme cases.

and

TerminateThread can result in the following problems:
If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.



i don't know what critical section means but i think i understand
how thread works.

so here is my idea.

1
2
3
4
5
6
7
8
9
10
11
12
13
bool issafetoexit = true;
void terminatemythread()
{
     while(1)
     {
           if(issafetoexit)
           {
                      TerminateThread(mythreadHANDLE, 0);
                      break;        
           }
           Sleep(40);
     }
}


everytime my thread is about to call functions outside my program
i shall set issafetoexit to false and after it has called the function then
set it true again.

Also if it is a function what will modify memory or give a call back later on
then i would set issafetoexit after that function has done doing what it was supposed to do.

Freeing all allocated memory by my thread after my thread is terminated.

Would that be safe?
thanks!
Would that be safe?

No!

You shouldn't need to use TerminateThread to control one of your own threads. You should signal to your thread to exit by setting a flag, an event, etc.

TerminateThread might be acceptable during app exit if a thread doesn't exit in a timely way when requested to exit. Other than that it shoudn't really turn up in normal app code.

You mention critical sections in your post. If you want to get into multi-threading you should study these along with other synchronization objects like events and mutexes.

Synchronization
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686353%28v=vs.85%29.aspx

Andy
Topic archived. No new replies allowed.