MultiThreading in C Tutorial - Part 4(pthread_detach)

At any point of time a thread can be in any one of the following states: joinable, detachable.By default if you are not modifying any attributes and has passed NULL as the second argument while the creation of thread(pthread_create) it will be in joinable state. Resources used by Joinable threads cannot be freed by himself, it has to freed by other threads using pthread_join.Resources used by detached threads cannot be freed by other threads,the resources are automatically freed on termination.So it is better to use pthread_detach if you are not doing any synchronization.

Syntax: int pthread_detach(pthread_t pthread);

Example Code:

#include <stdio.h>
#include <pthread.h>


void *threadFn(void *arg)
{

pthread_detach(pthread_self());
sleep(1);
printf("Thread Fn\n");
pthread_exit(NULL);
}

int main(int argc, char *argv[])
{

pthread_t tid;
int ret = pthread_create(&tid, NULL, threadFn, NULL);

if (ret != 0) {
perror("Thread Creation Error\n");
exit(1);
}
printf("After thread created in Main\n");
pthread_exit(NULL);
}

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig