从C中的2个线程获取返回值

时间:2012-09-25 15:22:14

标签: c pthreads

#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;
}

这个程序是如何工作的:我必须输入一个数字,这个程序会计算它是不是素数(我知道这是一个不好的算法,但我只需要学习 pthread )。
问题是返回的值太大了。
例如,如果我写“12”,tmp tmp_1 tmp_2的值为12590412 6295204 6295208
为什么我得到那些数字??

2 个答案:

答案 0 :(得分:1)

问题在于您的退货声明:

首先:

pthread_exit((void *)(&t_nums.tmp_1));
return NULL; 
}

如果您要返回并死亡,则无需调用pthread_exit()

其次,您正在返回一个地址(&amp;),这就是您正在打印的内容。试试这个:

return ((void *)(t_nums.tmp_1)); 
}

答案 1 :(得分:1)

一些注意事项:

  1. 请记住,pthread_exit的返回值仅适用于JOINABLE线程。在某些其他情况下,您可以使用不同的pthread类型(分离)。

  2. 在您的示例中,您返回的内容如下:void pthread_exit( void ** retval );

  3. 没有args时会有一个sigsegv。