_endthreadex(0) hangs - c++

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

Related

What happens to std::async call if parent/main thread dies

If I am right, the std::async uses a new thread and calls the method in it. I was wondering what happens if the main thread or the parent thread dies. Does the thread controlling the async method dies as well.
There is no concept of a "parent" thread in C++, each thread is independent of the one that it was created by. However, the main thread is special and if it returns from main() or calls exit() then the entire application is terminated even if other threads are still running. Once that happens, the program has undefined behaviour if the still-running threads access any global variables or automatic objects that were on the main thread's stack, or use any standard library objects or call any function not permitted in signal handlers.
In short, do not let other threads run after main completes if you expect sensible results.

Exit thread upon deleting static object during unload DLL causes deadlock?

I have one instance (global/static object) ClassA inside of my delay-loaded DLL. This object inside has an "Observer" thread which is required to perform graceful shutdown. When I call FreeLibrary I noticed that during deletion of this static object my thread requested to shutdown but hangs on _endthreadex() and causes deadlock. It doesn't matter if I call _endthreadex explicitly or implicitly. It doesn't matter if object is global or static - same result.
This thread wrapped in ClassB (implemented by template with custom message loop). There is a request to shutdown thread (post message) and following WaitForSingleObject which never returns for given thread heandle.
Same "template thread class" used everywhere in the code and shutdown works great. The only issue when deleting static obj. I think there is some lock inside of _endthreadex() which is already locked upon dll unload and deleting of static objects.
Thread started with _beginthreadex.
ps. When I instantiated same static obj inside of App - app closes without any significant issues.
Any ideas why _endtreadex causes deadlock? How to avoid it?
This particular case is easy to explain. The _endthreadex call needs the loader lock so that it can call DllMain with DLL_THREAD_DETACH. The thread that called FreeLibrary, however, already holds the loader lock, because you're already in the middle of a call to DllMain with DLL_PROCESS_DETACH.
The other way this can break is that if the process exits without explicitly unloading the library, your observer thread will be terminated before the DLL_PROCESS_DETACH call, so when you try to signal it to exit, it won't respond because it isn't running any more.
The best approach is probably to create explicit InitializeLibrary() and UninitializeLibrary() functions for the user to call.

WaitForSingleObject with thread handle get stuck while running regsvr32.exe

I have thread A that is creating another thread B, than thread A is waiting using WaitForSingleObject to wait until thread B dies.
The problem is that even though thread B returns from the thread's "thread_func", thread A does not get signaled!.
I know that because I added traces (OutputDebugString) to the end of the thread_func (thread B's main function) and I can see that thread B finishes its execution, but thread A never comes out of the WaitForSingleObject.
Now, I must also add that this code is in a COM object, and the scenario described above is happening when I'm calling regsvr32.exe (it get stuck!), so I believe that thread A is coming from the DLLMain.
Any ideas why thread A does not get signaled ?!?!
You could be hitting a problem with the loader lock. Windows, has an internal critical section that gets locked whenever a DLL is loaded/unloaded or when thread is started/stopped (DllMain is always called inside that lock). If your waiting thread A has that critical section locked (i.e. you are waiting somewhere from DllMain), while another thread B tries to shutdown and attempts to acquire that loader critical section, you have your deadlock.
To see where the deadlock happens, just run your app from the VS IDE debugger and after it gets stuck, break execution. Then look at all running threads, and note the stack of each one. You should be able to follow each stack and see what each thread is waiting on.
I think #DXM is right. The documentation on exactly what you can or can't do inside of DllMain is sparse and hard to find, but the bottom line is that you should generally keep it to a bare minimum -- initialize internal variables and such, but that's about it.
The other point I'd make is that you generally should not "call" regsvr32.exe -- ever.
RegSvr32 is basically just a wrapper that loads a DLL into its address space with LoadLibrary, Calls GetProcAddress to get the address of a function named DllRegisterServer, then calls that function. It's much cleaner (and ultimately, easier) to do the job on your own, something like this:
HMODULE mod = LoadLibrary(your_COM_file);
register_DLL = GetProcAddress(mod, "DllRegisterServer");
if ( register_DLL == NULL) {
// must not really be a COM object...
}
if ( S_OK != register_DLL()) {
// registration failed.
}

How do I close a thread safely?

pthread_create(&thread, NULL, AcceptLoop, (void *)this);
I have declared like this and inside of the AcceptLoop function I have infinity while loop. I'd like to close this thread when the server is closed. I have read pthread_cancel and pthread_join but I am not sure which one is better and safer. I would like to hear some detailed instructions or tutorials. Thanks in advance.
You don't need to do anything, just returning from the thread function will end the thread cleanly. You can alternatively call pthread_exit() but I'd rather return.
pthread_cancel() is scary and complicated/hard to get right. Stay clear if possible.
pthread_join() is mostly needed if you want to know when thread finishes and are interested in the return value.
Ooops, I'm wrong. It's been some time. In order for what I said to be true, you must detach from your thread. Otherwise you'll need to call pthread_join:
Either pthread_join(3) or
pthread_detach() should be called for
each thread
that an application creates, so that system resources for the thread
can be
released. (But note that the resources of all threads are freed
when the
process terminates.)
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_detach.3.html
I believe you would like to exit the worker thread by signalling from the main thread.
Inside AcceptLoop instead of looping infinitiely you loop on a condition, you can set the condition through your main thread, You will have to use some synchronization for this variable. Once the variable is set from main thread the worker thread AcceptLoop would break out and you can then call pthread_exit.
if you would like your main thread to wait for child thread to exit you can use pthread_join to do so.
In general, A child thread can exit in three conditions:
calling pthread_exit.
calling pthread_cancel.
The thread function returns.

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.
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