Four ways to exit threads in C and C++

  • 2020-04-02 01:05:19
  • OfStack

There are four ways to exit a thread:

1. Return of a thread function (preferably):
Among them, the return of the thread function is used to return, and the termination of the thread is the safest. After the return of the thread function, the class objects applied in the function will be cleaned up, that is, the destructor of these objects will be called. Then the function _endthreadex() will be automatically called to clean up _beginthreadex(...). The resource requested by the function (primarily the tiddata object created).

2. Call _endthreadex() or ExitThread() (preferably not):
If you exit the thread using these two methods, the return statement of the thread function will not be executed, so the destructor of the class object applied in the scope of the thread function will not be called, resulting in a memory leak.

The remaining two are important to avoid in programming.
3. Calling the TerminateThread() function from another thread in the same process (must be avoided);
4. Terminate the process where the thread is located (absolutely avoid);

But it would be a mistake to say that _endthreadex is completely useless, that _endthreadex is not an obsolete function, and that proper use is not a problem.
For example, in the main function of a thread, return is a good substitute for _endthreadex, just as in the main function return is a good substitute for exit() or ExitProccess(), but this does not mean that the exit function is useless. For example, if the thread calls a subfunction, the return is useless if the subfunction decides to exit the thread, and _endthreadex can terminate the thread.

But this design is not good, because it may cause the resource leakage proposed by LZ. Especially considering the background thread after the end of resource leaks than the main thread of resource leaks worse (dropped out after the main thread, process, the OS will clean up all resources, no leak does not leak, and the child thread exit left thread might also run for a long time, and may have a lot of the same type of child thread exits, can cause deadly leak)
Good design still returns the main function of the thread, leaving the threadproc to decide whether to exit, in the sense that _endthreadex is not necessary. Microsoft also points out that some programmers simply want to call the exit series of functions (ExitThread, ExitProccess, etc.) and have no choice but to provide them.


Related articles: