COMer
COMer

Reputation: 1137

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

alt text

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?

Upvotes: 2

Views: 1713

Answers (5)

Luke
Luke

Reputation: 11421

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.

Upvotes: 2

Romain Hippeau
Romain Hippeau

Reputation: 24375

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.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942040

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.

Upvotes: 0

Fyodor Soikin
Fyodor Soikin

Reputation: 80795

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

Upvotes: 2

wallyk
wallyk

Reputation: 57784

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.

Upvotes: 1

Related Questions