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.