Andreas Bonini
Andreas Bonini

Reputation: 44832

Trouble understanding MSDN's documentation on _beginthreadex and _endthreadex

I'm reading the documentation about _beginthreadex and _endthreadex but there are a few things I don't understand.

Note that the documentation keeps documenting the "extended" and normal functions at the same time, but I'm not using _beginthread and _endthread; only their extended versions.


You can call _endthread or _endthreadex explicitly to terminate a thread; however, _endthread or _endthreadex is called automatically when the thread returns from the routine passed as a parameter. Terminating a thread with a call to endthread or _endthreadex helps to ensure proper recovery of resources allocated for the thread.


_endthread automatically closes the thread handle (whereas _endthreadex does not). Therefore, when using _beginthread and _endthread, do not explicitly close the thread handle by calling the Win32 CloseHandle API.

Upvotes: 6

Views: 1554

Answers (2)

hxysayhi
hxysayhi

Reputation: 1987

Don't call _endthread or _endthreadex unless you want to quickly and abnormally terminate the thread. While the CRT will free its own per thread data, none of the C++ destructors for any of the thread's objects will be called. It behaves similarly to how _exit ends the process without calling destructors.

The normal means of ending a thread should be by returning from the function passed as an argument to _beginthread or _beginthreadex. This will result in C++ destructors being called as a normal part of the function return.

ref:https://stackoverflow.com/a/31257350/6364089

Upvotes: 0

Karel Petranek
Karel Petranek

Reputation: 15164

If _endthreadex is called automatically, how come calling it helps to ensure "proper recovery of resources"? It shouldn't make any difference whether I call it or not, or does it?

I think they meant this for the cases when you do not use a standard way of terminating your thread.

If _endthreadex does not close the handle, how come I shouldn't close it with CloseHandle?

You should close it with CloseHandle when using _endthreadex. The documentation says that only _endthread closes the handle (and therefore a CloseHandle call is superfluous).

All of my threads only voluntarily terminate by returning from their main function and are never forcefully terminated. According to the documentation, when this happens _endthreadex is called automatically.

Closing the thread handles from the thread that started it is a commonly-used solution. You should remember the handle and in appropriate place wait for the thread to finish (using WaitForSingleObject) and then close its handle. If you don't do that you will cause a leak of resources. That is usually not a big problem if you have a few threads but it is definitely not good practice.

Upvotes: 6

Related Questions