1
How to return an integer value and be able to show with printf using pthread ? Follow 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, ai is only returning the memory address of the variable and not the value itself.
In the function the expected value is printed but in main it does not appear correctly.
Perfect, worked out. Thanks.
– Beto