Home > Software design >  Returning value from Threads in C
Returning value from Threads in C

Time:12-13

I wanted to add two values and return them from the thread however I get the following error. My code is

main.c: In function ‘sum_thread’:
main.c:19:18: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   19 |     pthread_exit((void *)sum);
      |      

I was expecting the thread would return the sum and to print them. I want to be able to use the output of sum in main after a thread returns the value. `

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include<string.h>
#include <stdlib.h>
int global[2];

void *sum_thread(void *arg)
{
    int n1,n2,sum;
    n1=global[0];
    n2=global[1];
    sum = n1 n2;

    printf("N1   N2 = %d\n",sum);

    pthread_exit((void *)sum);
}

int main() 
{   
    void *status =0;
    printf("First number: ");
    scanf("%d",&global[0]);

    printf("Second number: ");
    scanf("%d",&global[1]);

    pthread_t tid_sum;
    pthread_create(&tid_sum,NULL,sum_thread,global);
    pthread_join(tid_sum,(void *)&status);

    return 0;
}

`

CodePudding user response:

Thank you so I ran the code and updated it a bit. But now I am stuck with getting the address instead of output. How do I fix this. For context here is the updated code and error

First number: 11
Second number: 12    
N1   N2 = 23
0x17

The code is given below:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include<string.h>
#include <stdlib.h>
int global[2];

void *sum_thread(void *arg)
{
    int n1,n2,sum;
    n1=global[0];
    n2=global[1];
    sum = n1 n2;

    printf("N1   N2 = %d\n",sum);

    pthread_exit((void *)(intptr_t)sum);
}

int main() 
{   
    void *status =0;
    printf("First number: ");
    scanf("%d",&global[0]);

    printf("Second number: ");
    scanf("%d",&global[1]); //hi

    pthread_t tid_sum;
    pthread_create(&tid_sum,NULL,sum_thread,global);
    pthread_join(tid_sum,(void *)&status);
    printf("%p",status);

    return 0;
}

CodePudding user response:

The compiler issues this warning whenever the value of an integer is converted to a pointer. As pointed out by @ikegami in a comment, you can fix it using a cast :

pthread_exit((void *)(intptr_t)sum);

and casting again in main:

printf("%d\n", (int)(intptr_t)status);

Don't forget to #include <stdint.h>

But if performance is not critical at this point, consider using dynamic memory:

int *sum = malloc(sizeof(int));

...
*sum = n1 n2;
printf("N1   N2 = %d\n", *sum);
pthread_exit(sum);

and in main:

pthread_join(tid_sum, &status);
printf("%d\n", *(int *)status);
free(status);

This has the advantage that you are not limited to integer types and is easier to debug.

  • Related