get return value from 2 threads in C

Posted by polslinux on Stack Overflow See other posts from Stack Overflow or by polslinux
Published on 2012-09-25T15:22:13Z Indexed on 2012/09/25 15:37 UTC
Read the original article Hit count: 190

Filed under:
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdint.h>
#include <inttypes.h>

typedef struct tmp_num{
    int tmp_1;
    int tmp_2;
}t_num;

t_num t_nums;

void *num_mezzo_1(void *num_orig);
void *num_mezzo_2(void *num_orig);

int main(int argc, char *argv[]){

    pthread_t thread1, thread2;
    int tmp=0,rc1,rc2,num;

    num=atoi(argv[1]);
    if(num <= 3){
        printf("Questo è un numero primo: %d\n", num);
        exit(0);
    }

    if( (rc1=pthread_create( &thread1, NULL, &num_mezzo_1, (void *)&num)) ){
        printf("Creazione del thread fallita: %d\n", rc1);
        exit(1);
    }
    if( (rc2=pthread_create( &thread2, NULL, &num_mezzo_2, (void *)&num)) ){
            printf("Creazione del thread fallita: %d\n", rc2);
            exit(1);
    }

    t_nums.tmp_1 = 0;
    t_nums.tmp_2 = 0;
    pthread_join(thread1, (void **)(&t_nums.tmp_1));
    pthread_join(thread2, (void **)(&t_nums.tmp_2));
    tmp=t_nums.tmp_1+t_nums.tmp_2;
    printf("%d %d %d\n", tmp, t_nums.tmp_1, t_nums.tmp_2);
    if(tmp>2){
        printf("Questo NON è un numero primo: %d\n", num);
    }
    else{
        printf("Questo è un numero primo: %d\n", num);
    }
    exit(0);
}

void *num_mezzo_1(void *num_orig){
    int cont_1;
    int *n_orig=(int *)num_orig;
    t_nums.tmp_1 = 0;
    for(cont_1=1; cont_1<=(*n_orig/2); cont_1++){
        if((*n_orig % cont_1) == 0){
            (t_nums.tmp_1)++;
        }
    }
    pthread_exit((void *)(&t_nums.tmp_1));
    return NULL;
}

void *num_mezzo_2(void *num_orig){
    int cont_2;
    int *n_orig=(int *)num_orig;
    t_nums.tmp_2 = 0;
    for(cont_2=((*n_orig/2)+1); cont_2<=*n_orig; cont_2++){
        if((*n_orig % cont_2) == 0){
            (t_nums.tmp_2)++;
        }
    }
    pthread_exit((void *)(&t_nums.tmp_2));
    return NULL;
}

How this program works: i have to input a number and this program will calculate if it is a prime number or not (i know that it is a bad algorithm but i only need to learn pthread).
The problem is that the returned values are too much big.
For example if i write "12" the value of tmp tmp_1 tmp_2 into the main are 12590412 6295204 6295208.
Why i got those numbers??

© Stack Overflow or respective owner

Related posts about c

    Related posts about pthreads