2. Thread creation in Linux

Main program implicitly create the starting thread. Other thread can be created by programmer with the help of pthread_create API.
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,  
                                 void *(*start_routine) (void *), void *arg);

pthread_create available in pthread.h header file

pthread_create arguments : 
  • thread - It is the unique identifier for each thread. This variable has pthread_t type
  • attr - This the variable used to set the properties for the thread. Set to NULL for default.
  • start_routine - This is the pointer function, this function executed when thread created
  • arg - argument passed to thread routine. 
When thread finishes the work pthread_exit routine will terminate the thread.

PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *t_function(void*);
 
void *t_function(void* arg) //thread handler
{
    long t_num = (long)arg;
    int x = 0;
    printf("thread created and running \n");
    printf("thread argument : %ld\n", t_num);
    while (x != 10){
        sleep(1);
        x++;
    }
    printf("thread finishes the work\n");
    pthread_exit(NULL);
}
 
int main(int argc, char *argv[])
{
    pthread_t mythread;
    int x = 0;
    long t_arg = 1;
    if((pthread_create(&mythread, NULL, t_function,  (void*)t_arg) != 0)){
        printf("Error, thread not created properly\n");
        exit(-1);
    }
    while(x != 5){
        sleep(1);
        x++;
    }
    printf("main finishes the work\n");
    pthread_exit(NULL);
}

OUTPUT : 
thread created and running 
thread argument : 1
main finishes the work
thread finishes the work

Program Explanation : 
  • Create mythread variable of type pthread_t
  • Create new thread with the help of pthread_create. In this pass arguments 1. thread variable, 2. NULL - it means not set any attributes for thread, 3. thread handler function, 4. variable name which passed to thread handler function, cast it to (void*). If don't want to pass any variable then set it to NULL
  • After pthread_create function main program and thread handler function independently.
  • main initially finishes the work, then thread will finish the work

Why we need pthread_exit in main?
       pthread_exit will kill thread.
       Thread created in the main process. If pthread_exit not there then after main finishes the work main process will terminated. 
       So all the thread inside the main process immediately killed without finishing there work. If we add pthread_exit it will kill the main thread and process will wait for all the thread to finishes the work.



No comments:

Post a Comment