Domanda

I am experimenting with thread library and I came across detached thread attribute. So i need to know Where and why to use Detached thread?? Thread which is detached from thread can stay in memory after main process has terminated??

È stato utile?

Soluzione 4

The space for the stacks of all threads in a process is carved out of the memory previously allocated for the stack of the process as a whole (shown in fig). Thus, the termination of the main program terminates the thread as well.

enter image description here

To illustrate: Write a program creating the threads in the detached state. Run the program with the gdb and you observe that the thread exits just when the program terminates.

Starting program: /home/avairavan/CProg/a.out [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Main Program Starting. [New Thread 0x7ffff77f5700 (LWP 3484)] Main Program Exiting. [Thread 0x7ffff77f5700 (LWP 3484) exited]

Altri suggerimenti

A detached thread is one that doesn't need to be "waited" with pthread_join. The thread just gets cleaned up when it returns.

This has no effect on the lifetime of the thread: if any thread (including the "main" one) calls _exit, all the threads die.

No, even detached Threads will be terminated when the main thread terminates.

You use detached threads when you don't want to join them later. In this case the OS may be able to clean up the thread without you joining it.

see: https://computing.llnl.gov/tutorials/pthreads/

A thread can live on even after the main thread ended, if the main thread was ended by a call to pthread_exit().

A detached thread cannot be joined and has its resources freed on termination, as opposed to a not detached thread which has its resources freed when it is joined.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top