3. Passing arguments to thread in Linux

Program contain in the previous thread post tell how to pass single argument to thread handler function. 

If you want to pass two or more variable to thread handler then need to define structure globally then pass the structure variable as argument when creating thread with the help of pthread_create.

program below will explain how to pass two or more variable to thread with the help  of structure.

PROGRAM : 
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *t_function(void *);
 
typedef struct _thread_stru{
    int var1;
    char var2;
    int var3;
}thread_stru;
thread_stru thrd_arg;
 
void *t_function(void *t_arg)
{
    thread_stru *data;
    int y = 0;
    data=t_arg;
    printf("Arguments -> %d %c %d\n", data->var1, data->var2, data->var3);
    while(y <= 10){
        sleep (1);
        y++;
    }
    printf("Thread finishes the work\n");
    pthread_exit(NULL);
}
   
   
int main(int argc, char *argv[])
{
    pthread_t mythread;
    int x = 0;
    thrd_arg.var1 = 10;
    thrd_arg.var2 = 's';
    thrd_arg.var3 = 20;
    if((pthread_create(&mythread, NULL, t_function, (void *)&thrd_arg)) != 0){
        printf("Error creating thread\n");
        exit(-1);
    }
    while(x != 5){
        sleep(1);
        x++;
    }
    printf("Main finishes the work\n");
    pthread_exit(NULL);
}

OUTPUT : 
Arguments -> 10 s 20
Main finishes the work
Thread finishes the work

No comments:

Post a Comment