The problem is that your main program closes the file and exits before the thread has finished running, that means that the thread might attempt to write to a closed file and that it will be killed with the process.
You must wait for the thread to finish before exiting the process. You can do this by, for example, using GetExitCodeThread
to poll for when the thread has exited.