MultiThreading in C Tutorial - Part3(pthread_exit and pthread_equal)

pthread_exit:
Syntax: void pthread_exit(void *retval);

pthread_exit has two different roles.If it is used in the main thread,it makes it to wait until all the user level threads terminates.If it is used in a thread function it will work like a exit call.

pthread_equal:
Syntax: int pthread_equal(pthread_t t1, pthread_t t2);

pthread_equal is used by the applications to compare two thread values.If two threads are equal, it returns a non zero value,otherwise it returns 0

Example Program:


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


pthread_t tid[2];


void *thread_fn(void *arg)
{

if(pthread_equal(tid[0], pthread_self()))
printf("Thread 0 in execution\n");
else
printf("Thread 1 in execution\n");
pthread_exit(NULL);
}

int main()
{

int i;
int ret;
for (i = 0;i < 2;i++) {
ret = pthread_create(&tid[i], NULL, thread_fn, NULL);
if (!ret)
printf("Thread[%d] created Successfully\n",i+1);
else
printf("Thread[%d] not created\n",i+1);

}
pthread_exit(NULL);
printf("After thread execution completed\n");
return 0;
}

Compile it with -lpthread flag to gcc

What is the difference between pthread_exit and pthread_join? Which we have to use at what position?

pthread_exit() will terminate the thread that is called.If you call it from your main thread,the main thread is terminated and your spawned threads continue execution.So anything you write after pthread_exit in the main thread will not be execcuted.This will be useful in a scenario in which your main thread has to just spawn threads.

pthread_join() will suspend the execution of the currently running thread until the particular thread you want is terminated,after that it resumes its execution.Useful where you have to wait until a particular thread completes its execution

If you write exit or return in your main thread , the whole process is terminated,but if you write pthread-exit in your main thread only that particular thread terminates and remaining threads continue their execution.

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto