How to return integer value in pthread?

1

How to return an integer value and can show with printf using pthread? Here is an example of the problem:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>   


void *somar(void *arg);
int main() {
    int res;
    pthread_t a_thread;
    void *thread_result;
    int n1=2;
    res = pthread_create(&a_thread, NULL, somar,&n1);
    if (res != 0 ) {
        perror("Erro\n");
        exit(EXIT_FAILURE);
    }
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) {
        perror("Join falhou");
        exit(EXIT_FAILURE);
    }
    int *aux1;
    aux1=malloc(sizeof(int));
    aux1=(int*)thread_result;
    int aux2 = *aux1;
    printf(" O valor da soma foi %d\n",aux2);
    exit(EXIT_SUCCESS);
}

void *somar(void *arg) {
    int *i;
    i = malloc(sizeof(int));
     i= (int*)arg;
    int soma=0;
    for(int j=1;j<=*i;j++){
        soma = soma +*i;
    }
    printf("Soma foi %d\n",soma);
    pthread_exit(&soma);
}

But apparently, there is only returning the memory address of the variable and not the value of it itself.

In the function the expected value is printed but in main it does not appear correctly.

    
asked by anonymous 31.10.2017 / 16:20

1 answer

1

The problem is that you are returning the address of a local variable. And this is a problem with or without threads. Since you are allocating a memory for your i (and not deallocating, which is another problem), use it as a bearer of the result:

//...
printf("Soma foi %d\n",soma);
*i = soma;
pthread_exit(i);

In the main function, thread_result will point to the value allocated within the thread. After reading it you should free the memory with:

free(thread_result);

The other memory allocation there is unnecessary.

    
31.10.2017 / 21:40