A.Cho
A.Cho

Reputation: 593

what means 'detach' in thread on the unix?

In the book, there are sentences:

By calling pthread_join(), we automatically place the thread with which we're joining in the detached state so that its resources can be recovered. If the thread was already in the detached state, pthread_join() can fail, returning EINVAL.

What means 'detach' in thread??

Upvotes: 1

Views: 165

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477600

Each thread owns resources, which are obtained when you create the thread. The resources need to be released when the thread's function has returned (just like you need to free memory that you allocated dynamically, or close file handles that you opened).

By default, the creator of the thread (= you) retains the ownership of the thread and the responsibility to reclaim its resources. You do this by calling join, which blocks until the thread's function returns and then destroys the thread resources.

Alternatively, you can put the thread into a "detached" state, in which case you no longer own it. The thread now "owns itself", and as soon as the thread function returns, the thread destroys itself. You cannot join a detached thread, and so you have no way of synchronizing on the thread's completion. (You could argue that that makes it a bad idea to ever detach a thread, since it means you're giving up on understanding the control flow of your program completely.)

Upvotes: 1

Related Questions