Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top