I have a Main thread that receives actions that take some time. So i create a thread and delegate the job to it. This execute function is being called by the main thread when it receives jobs. each job implement this execute.
Return_type execute( Arguments_here) {
// if a file read case
DWORD threadId;
HANDLE hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyAsyncFileRead, // thread function name
details, // argument to thread function
0, // use default creation flags
&threadId); // returns the thread identifier
// else do other work
}
Now since i do not want to wait on the main thread, i do not call WaitForSingleObject. [ my knowledge of windows thread is low. so if this is not required, pardon me ]
If i wait for the thread to close, it would wait my main thread. I do not want to do that. So when do i call CloseHandle ?
When one has got like 10 jobs in hand and one creates 10 threads and then wait for all 10 threads to finish, then it looks good to wait_for_multiple_objects and then call CloseHandle on each handle.
But what should i do in this case ?
[ I suppose that this question would be relevant for all OS so tagging them too. ]
If you really do not care about waiting for the thread, you can indeed close the handle immediately after creating the thread.
However, I strongly advise against doing that. You should always wait for threads to exit (preferrably in a clean, well-defined way). If not done earlier, wait for every thread you spawned when the program exits. Always, no exceptions.
Do not leave main
not knowing whether or not some other threads are still running. If need be, kill them the hard way (though preferrably, let them exit gracefully in a controlled manner, and wait for it).
If you don't wait for threads to finish, you may see weird crash-on-exit conditions. Or worse, you might not see them, and only have users/customers complain that one in a hundred times the config file gets corrupted (or worse, a data file of theirs)1. Now imagine that they are able to demonstrate step-by-step what they're doing, and you can tell that they do everything correctly, and there is no way something could go wrong.
Good luck figuring out that the crash is due to a still-running worker thread accessing some object (or global state) which was just deallocated by the exiting main thread, either explicitly or implicitly by the CRT.
Of course your stance could be that the worker thread will have exited long before the program finishes anyway, so why bother. However, that is playing Russian Roulette.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With