How to end _beginthreadex()? - c++

Inside my desktop application I have created a simple thread by using _beginthreadex(...). I wonder what happens if my application will be closed (without explicitly closing the thread)? Will all resources inside the thread be cleared automatically? I have doubts.
So I like to end the thread when my application will be closed. I wonder what would be the best practise?
Using _endthreadex is only possible inside(!) the thread and something like TerminateThread(...) does not seems to work (infinite loop). Do you have some advices?

When main exits your other threads will be destroyed.
It's best to have main wait on your other threads, using their handles, and send them a message (using an event, perhaps) to signal them to exit. Main can then signal the event and wait for the other threads to complete what they were doing and exit cleanly. Of course this requires that the threads check the event periodically to see if they need to exit.

When the main thread exits, the app and all of its resources are cleaned up. This will include other threads and their resources.
Also, post the code you have for TerminateThread, because it works.

The tidiest way is to send your thread(s) a message (or otherwise indicate via an event) that the tread should terminate and allow it to free its resources and exit its entry point function.

To close the thread, you need to call CloseHandle() with the handle returned by _beginthreadex.
The thread is part of the process, so when the process terminates it will take the thread with it and the operating system will resume ownership of everything the two own, so all the resources will be released.
Bear in mind that if you have not forewarned the thread that the-end-is-nigh, it may be in the middle of some work when it ends. If it is in the middle of using any system or external resources, they will be released but may be in a funky state (e.g. a file may be partially written, etc).
See also http://www.bogotobogo.com/cplusplus/multithreading_win32A.php
Note: Using CloseHandle() is only for _beginthreadex and not if you are using _beginthread. See http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.90).aspx

Related

When exactly does a non main GUI thread exit in Windows?

Say the main window of a GUI application creates a helper UI thread and the application closes. When and where will the application get a chance to clean up the thread resources? I know that the system automatically clears the resources but that doesn't help application specific resources like files etc.
As a test I had written MessageBox() in the destructors of window objects but they are not called from within the helper threads on closing the application.
It seems the systems simply shuts down the threads, may be via internal TerminateThread or some such call. Is there a way to know when exactly a thread with UI terminates and trap it?
I am using Win32 API not MFC etc.
Pseudocode
OnCreateHelperUI() // called from WndProc under appropriate message
CreateThread(...,UIThread,...)
return
UIThread()
Some auto objects on stack
Some dynamic objects on heap
CreateWindow()
while(GetMessage()){}
delete heap objects
return 0
The destructors of auto and heap objects aren't called.
FYI, waiting on the thread handle doesn't help. It simply lets the threads stick around forcing the user to close them individually. CloseHandle() will lead back to square one.
The thread closes when the thread function returns. The OS cannot do that for you, you must design it in. One good way is to have your main thread WM_CLOSE handler send a signal or message to the secondary thread. The secondary thread cleanly cleans up and returns (running destructors). While this is happening the main thread should be waiting on the thread handle, so it does not shut the app down until the secondary thread has shut down.

Notification on thread destroy

Is it possible to get notified if a thread had been destroyed? I've already seen such question here:
Notification when a thread is destroyed
The answer was: DLL_THREAD_DETACH, but it won't get called in case of TerminateThread.
So, my question is that, is it possible to detect even the termination? I don't want to prevent it, just get a notification if any of my threads got destroyed. I don't necessarily want to use DllMain, any solution would be great!
I'm working in a DLL, which get's injected into my main application, so I can't use WaitForSingleObject, since it suspends the main executable.
Thank you for each answer.
(P.s.: Just for understanding, my dll works the following way: Main application Loads the dll, on DLL_PROCESS_ATTACH, I open up some threads.)
Edit:
I forgot, I'm using windows & Visual Studio 2013.
Edit 2:
I came to that Disabling thread library calls, is useless. I mean it doesn't work the way I thought :) /I deleted that part, so it won't mislead anyone/
I would suggest having your DLL spawn its own worker thread that can then use WaitForSingleObject() on the handle of the thread that you need to monitor. The handle is signaled when the thread terminated, even when terminated by TerminateThread(). Better would be to use WaitForMultipleObjects() so that your DLL can signal the worker thread when it needs to terminate, such as with CreateEvent() and SetEvent(). That way the worker thread does not need to run a busy loop looking for a termination condition periodically.
I just readed documentation about DllMain():
If you terminate a thread by calling TerminateThread, the DLLs of that
thread do not receive DLL_THREAD_DETACH notifications.
So, in case thread termanatin you will not receive DLL_THREAD_DETACH.
The important think about DLL_THREAD_DETACH is that you will receive this notification in case "A thread is exiting cleanly"
You could run a watcher thread which will monitor all the threads you need and generate "no-more-the-thread" notifications.

How to make a new thread and terminate it after some time has elapsed?

The deal is:
I want to create a thread that works similarly to executing a new .exe in Windows, so if that program (new thread) crashes or goes into infinite loop: it will be killed gracefully (after the time limit exceeded or when it crashed) and all resources freed properly.
And when that thread has succeeded, i would like to be able to modify some global variable which could have some data in it, such as a list of files for example. That is why i cant just execute external executable from Windows, since i cant access the variables inside the function that got executed into the new thread.
Edit: Clarified the problem a lot more.
The thread will already run after calling CreateThread.
WaitForSingleObject is not necessary (unless you really want to wait for the thread to finish); but it will not "force-quit" the thread; in fact, force-quitting - even if it might be possible - is never such a good idea; you might e.g. leave resources opened or otherwise leave your application in a state which is no good.
A thread is not some sort of magical object that can be made to do things. It is a separate path of execution through your code. Your code cannot be made to jump arbitrarily around its codebase unless you specifically program it to do so. And even then, it can only be done within the rules of C++ (ie: calling functions).
You cannot kill a thread because killing a thread would utterly wreck some of the most fundamental assumptions a programmer makes. You would now have to take into account the possibility that the next line doesn't execute for reasons that you can neither predict nor prevent.
This isn't like exception handling, where C++ specifically requires destructors to be called, and you have the ability to catch exceptions and do special cleanup. You're talking about executing one piece of code, then suddenly ending the execution of that entire call-stack. That's not going to work.
The reason that web browsers moved from a "thread-per-tab" to "process-per-tab" model is exactly this: because processes can be terminated without leaving the other processes in an unknown state. What you need is to use processes instead of threads.
When the process finishes and sets it's data, you need to use some inter-process communication system to read that data (I like Boost.Interprocess myself). It won't look like a regular C++ global variable, but you shouldn't have a problem with reading it. This way, you can effectively kill the process if it's taking too long, and your program will remain in a reasonable state.
Well, that's what WaitForSingleObject does. It blocks until the object does something (in case of a thread it waits until the thread exits or the timeout elapses). What you need is
HANDLE thread = CreateThread(0, 0, do_stuff, NULL, 0, 0);
//rest of code that will run paralelly with your new thread.
WaitForSingleObject(thread, 4000); // wait 4 seconds or for the other thread to exit
If you want your worker thread to shut down after a period of time has elapsed, the best way to do that is to have the thread itself monitor the elapsed time in some way and then exit when the time is up.
Another way to do this is to monitor the elapsed time in the main thread or even a third, monitor type thread. When the time has elapsed, set an event. Your worker thread could wait for this event in it's main loop, and then exit when it has been raised. These kinds of events, which are used to signal the thread to kill itself, are sometimes called "death events." (Or at least, I call them that.)
Yet another way to do this is to queue a user job to the worker thread, which needs to be in an alterable wait state. The APC can then set some internal state variable which will trigger the death sequence in the thread when it resumes.
There is another method which I hesitate even mentioning, because it should only be used in extremely dire circumstances. You can kill the thread. This is a very dangerous method akin to turning off your sink by detonating an atomic bomb. You get the sink turned off, but there could be other unintended consequences as well. Please don't do this unless you know exactly what you're doing and why.
Remove the call to WaitForSingleObject. That causes your parent thread to wait.
Remove the WaitForSingleObject call?

Is it possible to create a thread that doesn't exit even when main thread exits in windows using c/c++?

Like in the above graph,all other threads will automatically exit once the main thread is dead.
Is it possible to create a thread that never dies?
You can, but you probably shouldn't; it will just end up confusing people. Here is a good explanation of how this works with Win32 and the CRT.
You can end the main() function's thread without returning from main() by calling ExitThread() on it. This will end your main thread, but the CRT shutdown code that comes after main() will not be executed, and thus, ExitProcess() will not be called, and all your other threads will continue to live on.
Although in this case, you must take care of ending all the other threads correctly. The process will not terminate while there is at least one thread that is not "background".
If main() is careful not to call ExitProcess() (or whatever it's called that happens when main returns) until all threads have terminated, that is easily done. Just don't exit main until it's done.
Not really. The CRT startup code calls main(), then calls exit(). That terminates the program, regardless of any other threads.
You would have to prevent main() from returning. Normally done with WaitForSingleObject() on the thread handle.
In this specific case, if you see the threads still running when you trace through main's return then you forgot to release/close the Win32 resource you are using.
It looks like it might not be possible as you can see from the other answers. The question is why would you want to do this ? By doing this you are going against the intended design of the OS.
If you look at this : http://msdn.microsoft.com/en-us/library/ms684841(VS.85).aspx
You will see that a Thread is meant to execute within the context of a process and that in turn a fiber is intended to operate withing the context of a thread.
By violating these premises you will potentially end up having issues with future operating system upgrades and your code will be brittle.
Why do you not spawn another process and keep it in the background ? That way you can terminate your original process as desired, Your users will still be able to terminate the spawned process if they desire.

Stopping an MFC thread

I understand the problem with just killing the thread directly (via AfxEndThread or other means), and I've seen the examples using CEvent objects to signal the thread and then having the thread clean itself up. The problem I have is that using CEvent to signal the thread seems to require a loop where you check to see if the thread is signaled at the end of the loop. The problem is, my thread doesn't loop. It just runs, and the processing could take a while (which is why I'd like to be able to stop it).
Also, if I were to just kill the thread, I realize that anything I've allocated will not have a chance to clean itself up. It seems to me like any locals I've been using that happen to have put stuff on the heap will also not be able to clean themselves up. Is this the case?
There is no secret magic knowledge here.
Just check the event object periodically throughout the function code, where you deem it is safe to exit.
Does your thread ever exit? If so, you could set an event in the thread at exit and have the main process wait for that event via waitforsingleevent. This is best to do with a timeout so the main process doesn't appear to lockup when it's closing. At the timeout event, kill the thread via AfxKillThread. You'll have to determine what a reasonable timeout is, though.
Since you don't loop in the thread this seems to me to be the only way to do this. Of course, you could something like set a boolean flag in the main process and have the thread periodically check this flag, but then your thread code will be littered with "if(!canRun) return;" type code.
If the thread never exits, then AfxKillThread/AfxTerminateThread is the only way to stop the thread.
Locals would be placed on the stack and, hence, WOULD be freed on forcing the thread shut (I think). Destructors won't get called though and any critical sections the thread holds will not get released.
If the thread is ONLY doing things with simple data types on the stack, however, it IS a safe thing to be doing.