In this blog post we will see a pthread attributes example. consider a case where there is a need for main thread not to wait for its child thread. We cannot achieve this requirement if we create a thread using  pthread_create(&thread_id, NULL, foo, NULL) because if have passed null attribute to the pthread_create api. Let see below code.

In the above program the main thread waits for child because we have called pthread_join. By default when a thread is created its state is join-able. if we want to change the behavior of newly created child thread then we have to modify the attributes of target thread.  This behavior can be achieved by making the child thread a detached thread.  Following are the steps to create detached thread.

  • Initialize a thread attribute using pthread_attr_init(pthread_attr_t *attr)
  • Set the state of thread  detached. ( pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate))
  • Create thread using attribute (*atrr) , pthread_create(&thread_id, &attr, start_function, (void*)”argument”).

pthread attributes example in c

Compile and run

 




Related Contents to follow