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