Trouble understanding MSDN's documentation on _beginthreadex and _endthreadex - c++

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.
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?
_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.
If _endthreadex does not close the handle, how come I shouldn't close it with CloseHandle?
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.
This though won't close the handle. Assuming that I do need to close it, notwithstanding with what is said above, how can I do that since at this point the thread is dead? Should I somehow close it from another thread? What happens if I leave it open?

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.

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

Related

How to properly use _beginthread and endthread

I'm used to work with good old WinAPI call CreateThread(), and check thread's status using the waiting function, e.g WaitForSingleObject(), Once thread thread is signaled with WAIT_OBJECT_0, i close it using CloseHandle().
Recently I've decided to move to beginthread and somehow avoid the risks of uninitialized crt and accidental memory leaks that may happen.
Doing that got me confused.
What's the exact purpose of endthread()? why when i call CloseHandle() in the main function, after thread's execution, CloseHandle() crashes with invalid handle?
Should i ever close the handle returned by beginthread?
endthread, As i understood is invoked automatically by the thread once my function goes out of scope, so should i call it anyway just before i get out of scope?
According to msdn, endthread already calls CloseHandle() 1.From where does the thread obtain a reference / instance to its handle. 2. If i do insist on using endthread(), should it be the last command in the thread?
thanks
EDIT: MSDN paper describing the leaks, here.
As stated in the comments by David Hefferman you can simply change your code back to using CreateThread. The Visual C++ runtime (CRT) will automatically initialize the CRT's per thread data the first time you use a function that uses the per thread data.
The CRT will also automatically free the per thread data when a thread ends, so using CreateThread won't cause memory leaks. There is one exception, if all of the following conditions are true then per thread data isn't automatically freed:
You're building an executable, not a DLL
You're linking against the static version of the CRT library (LIBCMT.LIB) instead of the DLL version (MSVCRT.LIB)
The executable you built is run under Windows XP (or an earlier version of Windows).
Note that even if all this true in your case, the memory leak isn't going to be significant unless you're creating a long lived application that creates and destroys hundreds of thousands of threads over its life time.
If you still want to use the CRTs thread creation functions (_beginthread/_beginthreadex) you should follow these guidelines:
Never use the handle returned by _beginthread. With _beginthread the thread handle is automatically closed when the thread exits, which can potentially happen before _beginthread even returns. You can't use it with WaitForSingleObject safely because the thread might have already exited before you call this function. If you want to use the thread handle for anything use _beginthreadex instead.
You should never close the handle returned by _beginthread. The CRT will do it automatically, and as described in the previous point, may do so before you have chance to.
You should always close the handle returned by _beginthreadex when you no longer need it. The CRT won't do this automatically for you, so it's your own responsibility.
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.

Who's responsibility is it to call CloseHandle() for Thread handle

I have a class Class in which there's a member property HANDLE handle to a thread (We can assume it is set to NULL at that point) . at some point , a method within Class dispatches one of it's own methods Class::threaded() (using another function that is external to the class itself, but it doesn't really matter here) with CreateThread(). The calling thread will then may continue to other function outside of Class.
As CloseHandle() must be called for the HANDLE returned from CreateThread() , I was wondering if calling it from Class::threaded() just before it returns would be a decent solution.
Two basic ways to deal with a thread. Commonly you're interested when the thread terminates, you'll need to keep the handle around so you can find out. And of course you'll close it after you detected termination. Or you don't care, fire-and-forget style, or have additional synchronization objects to signal that the thread function completed and/or you ask it to exit. In which case you simply close the handle as soon as you start it.
Do keep in mind that it is not necessary to keep the handle opened to keep the thread running, in case that's the source of the confusion.
You receive a handle to the thread so you can manage it. If there is no need to it, you can call CloseHandle right away.
Closing the HANDLE will have no terminate the thread, so, it's secure to close it if nothing from the thread is of interest to you.
You can close it as soon as you are through using it. Closing it has no effect on the thread. (The handle is reference counted by OS.)

Where do I use _endthreadex - windows API

I am a novice in the windows API, and recently I learned I should not use CreateThread and TerminateThread. I switched to _beginthreadex, however I am not sure how I am supposed to use _endthreadex?
For example, here is a basic function I was testing with:
// MyThreadFunction - outputs "#.) I Work" and ends
unsigned int __stdcall MyThreadFunction( void * lpParam )
{
int i = (int)lpParam;
cout << i << ".) I work! " << endl;
_endthreadex(0);
return 0;
}
Is my placement of _endthreadex correct? I have it before the return 0, which just seems odd to me? I read in the msdn pages about _endthreadex that it is called automatically when a function ends, but you should call it for better memory cleanup, and that is why I tried putting it in. It just doesn't seem right, sorry if this is a bad question. I just want to make sure I am doing everything right to the best of my abilities
You actually don't need to call _endthreadex() at all. It will be called for you automatically after your thread function returns anyway.
The answer is already given in short version, and if you fancy to know more - the return from your function will actually be used as an argument in _endthreadex call. Here is what runtime is doing when you start a thread. The thread is indeed started with a starting point somewhere in CRT, where internal _callthreadstartex is doing:
_endthreadex(MyThreadFunction(...));
That is, as soon as you return, _endthreadex will be immediately called for you and it will exit from the thread.
Can you use it explicitly? Yes you can, and your code is also good because it does not matter much whether you call it yourself or it will be called for you, provided that no leaks take place on the way (such as, in particular, not yet called destructors of local variables).
Since it will anyway be called for you, and return from function is safer in terms of freeing local resources, there is no use, advantage and sense to make an explicit call.
MSDN basically explains exactly the same right there in Remarks section.
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 to
_beginthread or _beginthreadex. Terminating a thread with a call to endthread or _endthreadex helps ensure proper recovery of resources
allocated for the thread.
You don't have to call it, as already mentioned. Concerning your code, I think that the final return 0; will not even be called because _endthreadex() never returns. This could also cause destructors of local objects not to be called (which is what I believe the MSDN wanted to say), so using this function could even be harmful in C++. Consider using Boost.Thread, they have an exception dedicated specifically to ending a thread, which should do the right thing if you want to terminate the thread somewhere in the middle.

Do threads clean-up after themselves in Win32/MFC and POSIX?

I am working on a multithreaded program using C++ and Boost. I am using a helper thread to eagerly initialize a resource asynchronously. If I detach the thread and all references to the thread go out of scope, have I leaked any resources? Or does the thread clean-up after itself (i.e. it's stack and any other system resources needed for the itself)?
From what I can see in the docs (and what I recall from pthreads 8 years ago), there's not explicit "destory thread" call that needs to be made.
I would like the thread to execute asynchronously and when it comes time to use the resource, I will check if an error has occured. The rough bit of code would look something like:
//Assume this won't get called frequently enough that next_resource won't get promoted
//before the thread finishes.
PromoteResource() {
current_resource_ptr = next_resource_ptr;
next_resource_ptr.reset(new Resource());
callable = bind(Resource::Initialize, next_resource); //not correct syntax, but I hope it's clear
boost::thread t(callable);
t.start();
}
Of course--I understand that normal memory-handling problems still exist (forget to delete, bad exception handling, etc)... I just need confirmation that the thread itself isn't a "leak".
Edit: A point of clarification, I want to make sure this isn't technically a leak:
void Run() {
sleep(10 seconds);
}
void DoSomething(...) {
thread t(Run);
t.run();
} //thread detaches, will clean itself up--the thread itself isn't a 'leak'?
I'm fairly certain everything is cleaned up after 10 seconds-ish, but I want to be absolutely certain.
The thread's stack gets cleaned up when it exits, but not anything else. This means that anything it allocated on the heap or anywhere else (in pre-existing data structures, for example) will get left when it quits.
Additionally any OS-level objects (file handle, socket etc) will be left lying around (unless you're using a wrapper object which closes them in its destructor).
But programs which frequently create / destroy threads should probably mostly free everything that they allocate in the same thread as it's the only way of keeping the programmer sane.
If I'm not mistaken, on Windows Xp all resources used by a process will be released when the process terminates, but that isn't true for threads.
Yes, the resources are automatically released upon thread termination. This is a perfectly normal and acceptable thing to do to have a background thread.
To clean up after a thread you must either join it, or detach it (in which case you can no longer join it).
Here's a quote from the boost thread docs that somewhat explains that (but not exactly).
When the boost::thread object that
represents a thread of execution is
destroyed the thread becomes detached.
Once a thread is detached, it will
continue executing until the
invocation of the function or callable
object supplied on construction has
completed, or the program is
terminated. A thread can also be
detached by explicitly invoking the
detach() member function on the
boost::thread object. In this case,
the boost::thread object ceases to
represent the now-detached thread, and
instead represents Not-a-Thread.
In order to wait for a thread of
execution to finish, the join() or
timed_join() member functions of the
boost::thread object must be used.
join() will block the calling thread
until the thread represented by the
boost::thread object has completed. If
the thread of execution represented by
the boost::thread object has already
completed, or the boost::thread object
represents Not-a-Thread, then join()
returns immediately. timed_join() is
similar, except that a call to
timed_join() will also return if the
thread being waited for does not
complete when the specified time has
elapsed.
In Win32, as soon as the thread's main function, called ThreadProc in the documentation, finishes, the thread is cleaned up. Any resources allocated by you inside the ThreadProc you'll need to clean up explicitly, of course.

_endthreadex(0) hangs

I have some code which I did not originally create that uses _beginthreadex and _endthreadex. For some reason, when it calls _endthreadex(0), the call just hangs and never returns. Any ideas as to what would normally cause this call to hang?
My answer is too far late, but still someone will use it.
In my case _endthreadex hanged when I unload dll and deleted some global objects. One of global objects had another thread inside and that thread also performed thread exit. This caused deadlock since DLLMain already locked crt memory map. Read DLLMain help and find that you are not allowed do any other action on another threads or processes during DLLMain call.
_endthreadex ends the thread, so it can't return. That's the whole point of calling it.
EDIT: It's a bit unusual to call _endthreadex, normally you just let the thread start procedure return and the runtime calls _endthreadex for you. You may need to explain a bit more, what you are trying to do before we can help.
Are you mistakenly calling _endthreadex() to attempt to end a thread from the main thread?
The function _endthreadex() is meant to be called inside the thread that you want to terminate to report a return value, and for the proper "recovery of resources allocated for the thread." You shouldn't need to call it in a destructor from the main thread. You could, in a destructor, signal to the thread via an event (see SetEvent, called from the main thread) that the thread should exit as soon as possible, and then the thread that is exiting as its last statement would call _endthreadex().
Calling _endthreadex() in your main thread would cause the process to hang, because you've terminated your main thread, but you would still have the original thread you wanted to terminate still running.
Ok....well, endthreadex gets called in the deconstructor of my class via "delete classinstance"...and that deconstructor call never returns...so the whole thing hangs