How to return integer value in pthread?

Asked

Viewed 318 times

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.

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 to your i (and not dislocating, which is another problem), take advantage to use it as the result carrier:

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

In function main, 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.

  • Perfect, worked out. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.