Thread Detachment in Pthread

After #thread creation, one would have the need to detach these threads from the main process especially when the main function has a large code section to execute with. To do this, there are two ways in Pthread library: call pthread_detach or set pthread_attr_t upon the thread creation.

pthread_detach is straight forward, we could just pass in the thread that we want to detach:

pthread_detach(th); // Detach thread `th`

However, a much better way to do this is by setting the thread’s attribute. This is where pthread_attr_t comes in handy. Since pthread_attr_t is an object, we need to initialise it by calling pthread_attr_init. After that, set the attribute PTHREAD_CREATE_DETACHED by calling the function pthread_attr_setdetachstate. When creating a thread using pthread_create, pass in the attribute in its second parameter. Lastly, destroy it like any other objects by calling pthread_attr_destroy. In this way, we could avoid excessive cost on function calling in a for loop.

pthread_attr_t attr;

// in the program
pthread_attr_init(attr);
// to detach the thread
pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

// in thread creation
pthread_create(&th, &attr, &routine, NULL)

// at the end of the program
pthread_attr_destroy(attr);
#multithreading #pthread