This seems rather silly... but I have to ask.
When CreateThread is called, and a thread is successfully created, let's say that thread enters an infinite loop, e.g.:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <windows.h>
#include <iostream>
DWORD WINAPI ThreadFunc(void* data)
{
while (1) {
std::cout << "ping" << std::endl;
Sleep(1000);
}
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
CloseHandle(handle);
while (1) { Sleep(60 * 1000); }
}
| |
If I Ctrl+C to force the process to stop, is Windows smart enough to also kill the child thread, or does this create "thread leak" that exists even after my process is stopped?
(Note that CloseHandle is designed to not actually stop the thread, so it shouldn't have an effect here, but for purposes of the argument, let's say that a logic error prevented CloseHandle from being called.)
Edit: I think I found the answer here
https://stackoverflow.com/questions/4666628/do-child-threads-exit-when-the-parent-thread-terminates
The SO post is tagged for Windows, and states
There is no parent/child relationship between threads. If thread A creates thread B and then thread A terminates, then thread B will continue to execute.
The exception to this is when the main thread (that is, the thread that runs the main() function) terminates [...] the process terminates and all other threads stop. |
So by this, I conclude that killing the main process will kill the child thread which is in an infinite loop.
I could also test this by writing a file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
DWORD WINAPI ThreadFunc(void* data)
{
std::ofstream ofs("temp.txt");
unsigned i = 0;
while (1)
{
ofs << "flush " << i++ << std::endl;
std::cout << "ping" << std::endl;
Sleep(5000);
}
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
CloseHandle(handle);
while (1) { Sleep(60 * 1000); }
}
| |
And confirmed... it isn't creating zombie files. Solved.