Friday 13 September 2013

Pass multiple arguments in pthread_create

Leave a Comment
Pthreads

        Posix thread normally known as pthread. It is an API to create threads on Unix like operating system such as GNU/Linux, MAC etc. Windows doesn't provide support for this API. In Windows some third party softwares are available which can be used for writing multithread application using pthread, pthreads-w32 is one of this.
        To create thread pthread uses pthread_create function with syntax given below.

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
        This function creates a new thread and that thread will execute the function specified as third parameter with arguments specified in fourth parameter. There is no provision to transfer more than one argument to the function which is called by pthread_create.
        If you want to transfer multiple arguments then you require to create a structure with arguments you require to pass to the function and then by transferring this structure you can pass as many arguments as you want to transfer. The program pthread.c below is one such example of passing multiple parameters


#include"pthread.h"
#include"stdlib.h"
#include"stdio.h"

struct test
{
 int var1,var2;
 float var3;
};

typedef struct test struct1;

void* fun1(void* a)
{
 struct1 *b;
 b=(struct1*)a;
 b->var3=b->var1+b->var2;
 printf("\nOperation successful the sum is %f\n",b->var3);
}

int main()
{
 pthread_t th1,th2;
 struct1 *a;
 a=(struct1 *)malloc(sizeof(struct1));
 a->var1=10;
 a->var2=20;
 pthread_create(&th1,NULL,fun1,(void*) a);
 pthread_join(th1,NULL);
 return 0;
}


0 comments:

Post a Comment