shank
shank

Reputation: 31

thread management in C

defining the struct

typedef struct {
    int a,b;
}targ;

1st thread function:

void* sum(void *arg) {
    int *s;
    targ *p = (targ*)arg;

    int i=p->a;
    int j=p->b;
    *s=i+j;
    pthread_exit((void*)s);
}

2nd thread function:

void* pdt(void *arg) {
    int *p;
    targ *s= (targ*)arg;

    int i=s->a;
    int j=s->b;
    *p=i*j;
     pthread_exit((void*)p);
 }

Main thread function:

 int main(void) {
     int ret1,ret2;
     pthread_t tid1,tid2;
     targ *x;

     x=(targ*)malloc(sizeof(targ));

     printf("enter the 2 numbers\n");
     scanf("%d%d",&x->a,&x->b);

     printf("%d%d",x->a,x->b);

     pthread_create(&tid1,NULL,sum,(void*)x);
     pthread_create(&tid2,NULL,pdt,(void*)x);

     pthread_join(tid1,(void**)&ret1);
     pthread_join(tid2,(void**)&ret2);

     printf("the sum and product of the 2 numbers is %d and %d\n",(int)ret1,    (int)ret2);

     return 0;
 }

I'm not able to understand why there's a segfault even though I have followed the man pages for each API.

The program is to understand how thread functions work with one another. The main function passes the values to each thread function and they return back a value to the main function.

Upvotes: 2

Views: 81

Answers (2)

G. Emadi
G. Emadi

Reputation: 230

You have not allocated memory for the s and p pointer variables. So the segmentation fault happened. You should allocate memory or use the address only.

Upvotes: 3

2501
2501

Reputation: 25753

Your method of returning and printing the return values from the threads is not correct. I will show the step by step solution for one thread. The other has the same solution.

In the thread function sum, allocate some memory for an int variable, then store the result in the memory pointer to by s.

int *s = malloc( sizeof(int) );
*s=i+j

Then return the pointer to that memory.

return s;

Now you need to collect the pointer returned from the thread correctly.

The function pthread_join requires a pointer to a pointer to void as the second argument. You are passing a pointer to an int. This is incorrect even though the cast suppresses the error. Instead use a pointer to void and pass its address to the function:

void* ret1 = NULL;
pthread_join(tid1, &ret1);

The pointer ret1 now points to the same memory, pointer s pointed to in the thread. That memory holds the result of the calculation. Declare a pointer to int and store pointer to that memory in it:

int* sm = ret1;

Then print the value:

printf( "%d\n" , *sm );

After it is not needed anymore the memory allocated in the function sum(Look at the malloc call above) should be freed:

free( sm );

Upvotes: 1

Related Questions