What is the difference between a detached thread and a daemon thread?

sgowd picture sgowd · Aug 10, 2012 · Viewed 15.9k times · Source

I understand that all daemon threads are detached threads, but why are all detached threads not daemon?

Say thread "main" creates thread "A"(non-detached) and thread "A" creates thread "B"(detached). Can thread "A" exit while "B" continues running?

PS: I am asking with reference to pthreads, but please do answer regardless.

Answer

enthusiasticgeek picture enthusiasticgeek · Feb 5, 2013

Maybe you should first read What is the difference between fork and thread?

To elaborate more

Daemon Thread

Typically in C/C++ (Linux Environment) one would create a daemon using fork(). fork() creates a new process by duplicating the calling process. Here the parent process would exit leaving the the child process behind. This child process detaches from the controlling terminal, reopens all of {stdin, stdout, stderr} to /dev/null, and changes the working directory to the root directory. (based on flags, of course). Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

Detached Thread

While Pthread detached behavior is different (1) The detached thread cannot be joined back once detached (2) The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit (or equivalently, if the main thread returns). The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are automatically released back to the system without the need for another thread to join with the terminated thread.