Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_detach question

Tags:

Till recently, I was under the impression that if you "detach" a thread after spawning it, the thread lives even after the "main" thread terminates.

But a little experiment (listed below) goes contrary to my belief. I expected the detached thread to keep printing "Speaking from the detached thread" even after main terminated, but this does not seem to be happening. The application apparently terminates...

Do the "detached" threads die after "main" issues return 0?

#include <pthread.h> #include <stdio.h>  void *func(void *data) {     while (1)     {         printf("Speaking from the detached thread...\n");         sleep(5);     }     pthread_exit(NULL); }  int main() {     pthread_t handle;     if (!pthread_create(&handle, NULL, func, NULL))     {         printf("Thread create successfully !!!\n");         if ( ! pthread_detach(handle) )             printf("Thread detached successfully !!!\n");     }      sleep(5);     printf("Main thread dying...\n");     return 0; } 
like image 965
puffadder Avatar asked May 18 '11 10:05

puffadder


People also ask

What is pthread_detach used for?

The pthread_detach() function is used to indicate to your application that storage for the thread tid can be reclaimed when the thread terminates. Threads should be detached when they are no longer needed. If tid has not terminated, pthread_detach() does not cause the thread to terminate.

What happens if Pthread_join is not called?

If you want to be sure that your thread have actually finished, you want to call pthread_join . If you don't, then terminating your program will terminate all the unfinished thread abruptly.

What does Pthread_self return?

The pthread_self() function returns the ID of the calling thread. This is the same value that is returned in *thread in the pthread_create(3) call that created this thread.

What are pthreads in operating system?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.


1 Answers

To quote the Linux Programmer's Manual:

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(3) (or equivalently, if the main thread returns).

Also from the Linux Programmer's Manual:

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

like image 150
NPE Avatar answered Nov 08 '22 09:11

NPE