3

I was just wondering, if I create a detached thread (POSIX) using an attribute and the function "pthread_attr_setdetachstate" with the argument PTHREAD_CREATE_DETACHED, do I have to destroy the thread at the end of my program ?

I know that I have to destroy the attribute created to create the detached thread but for the thread itself, I don't really know.

tod
  • 1,539
  • 4
  • 17
  • 43
Dust009
  • 315
  • 2
  • 10
  • 2
    What do you consider "*destroy a thread*" to do? – alk May 15 '14 at 11:42
  • You're right that "destroy" is not the best word to describe it, but I was wondering, as a normal thread is terminated with the function "pthread_join", maybe the detached thread needed another function to be properly terminated at the end of the program. – Dust009 May 15 '14 at 21:45
  • `pthread_join()` does not terminate any thread. It blocks (waits) until the thread "referenced" ended and then tells the OS to free this ended thread's resources. This however is specfied for joinabe threads only, that is threads that haven't been detached. – alk May 17 '14 at 11:39

2 Answers2

5

I don't think you should destroy the detached thread.

Consider threads as processes which share the same memory region. So when a process is forked and child process is completed before the main process, then the return value of the child process is held in kernel memory which can be taken up by parent process.

Detaching a thread is nothing but the indication to theh kernel that theh thread's return or exit status is not required and can be ignored once the thread is completed.

So you don't have to wait for the detached thread to complete at theh end of program since in most POSIX systems, if theh main thread is completed then other threads of that process are also stopped by the system so it is a good idea to wait for the child threads to complete before exiting from main.

alk
  • 69,737
  • 10
  • 105
  • 255
user3494614
  • 603
  • 1
  • 7
  • 20
3

Upto my understanding:

If you don't want to collect the exit state of thread, then you can use PTHREAD_CREATE_DETACHED.So kernel will take care of cleaning up the thread specfic resources after the thread ended. And once you set the detached state. you can't revert to joinable state.

So you can destroy the attribute anywhere in the program.

gangadhars
  • 2,584
  • 7
  • 41
  • 68