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.

#include <stdio.h>
#include<unistd.h>
#include <pthread.h>
#include<stdlib.h>
 
void *foo(void *vargp)
{
    sleep(5);
    printf("Hello from Thread \n");
}
 
int main() {
    pthread_t thread_id;
    printf("Creating a Thread....\n");
    pthread_create(&thread_id, NULL, foo, NULL);
    pthread_join(thread_id, NULL);
    return 0;
}

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

int thread_finished = 0;

void* thread_function(void* value) {
	printf("%s is in threa_function.\n", (char*) value);
	sleep(5);
	thread_finished = 1;
	printf("%s is now leaving the thread function.\n", (char*) value);
	pthread_exit(value);
}

int main()
{
	pthread_attr_t attr;
	pthread_t thread_id;

	int res;
	res = pthread_attr_init(&attr);
	if (res != 0) {
		printf("init failed \n");
		exit(-1);
	}

	res = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	if (res != 0) {
		printf("Setting detached state failed\n");
		exit(-1);
	}

   if(pthread_create(&thread_id, &attr, thread_function, (void*)"Child Thread"))
	   printf("Error creating thread\n");

	while(!thread_finished) {
		printf("Waiting for child thread to finish.\n");
		sleep(1);
	}

	printf("Child thread finished.\n");
	// destroy attr
	pthread_attr_destroy(&attr);

	return 0;
}

Compile and run

bosch@bosch-Inspiron-N5050:~$ gcc -g thread.c -lpthread
bosch@bosch-Inspiron-N5050:~$ ./a.out 
Waiting for child thread to finish.
Child Thread is in threa_function.
Waiting for child thread to finish.
Waiting for child thread to finish.
Waiting for child thread to finish.
Waiting for child thread to finish.
Child Thread is now leaving the thread function.
Child thread finished.

 



Related Contents to follow