POSIX返回并打印数组prthread_join()?

问题描述 投票:0回答:1

我试图找到多个数字的素数因子分解。如果用户键入15 80 77,它将为每个输入创建一个线程,并让线程返回一个分解数组,然后打印。但是我收到了两个错误。一个说错误:解除引用'void *'指针[Werror] printf(“%d”,returnValue [r]);

并且表示错误:无效使用void表达式printf(“d”,returnValue [r]);

我并不熟悉指针。任何帮助是极大的赞赏。这也是我的第一个问题,请耐心等待。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


typedef struct _thread_data_t {
    int tid;
} thread_data_t;

void *runner(void *param);

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

    pthread_t thr[argc];
    pthread_attr_t attr;
    int i, rc;
    //int *primeFactor;
    //primeFactor = (int *)malloc(sizeof(int)*argc);
    //thread_data_t thr_data[argc];
    printf("Prime Numbers: ");

    //Get the default attributes
    pthread_attr_init(&attr);
    //creat the thread
    for(i = 0; i < argc; ++i){
        //thr_data[i].tid = i;
        if ((rc = pthread_create(&thr[i],&attr,runner,argv[i]))){
            fprintf(stderr, "error: pthread_create, rc: %d\n", rc);
            return EXIT_FAILURE;
        }
    }

    //Wait for the thread to exit
    for(i = 0; i<argc; ++i){
        void *returnValue;
        int r = 0;
        pthread_join(thr[i], &returnValue);
        for(r = 0; r < sizeof(returnValue); r++){
            printf("%d ", returnValue[r]);
        }
    }
    printf("\nComplete\n");

}

//The Thread will begin control in this function
void *runner(void *param) {
    int *primeFactors;
    int num = atoi(param);
    primeFactors = (int *)malloc(sizeof(int)*num);
    int i, j, isPrime;
    int k = 0;
    for(i=2; i<=num; i++)
    {
        if(num%i==0)
        {
            isPrime=1;
            for(j=2; j<=i/2; j++)
            {
                if(i%j==0)
                {
                    isPrime = 0;
                    break;
                }
            }

            if(isPrime==1)
            {
                primeFactors[k] = i;
                k++;
            }
        }
    }


    //Exit the thread
    //      pthread_exit(0);

    //      pthread_exit((void *)primeFactors);
    pthread_exit(primeFactors);
}
c pthreads posix pthread-join
1个回答
0
投票

您在代码段中犯了几个错误。

  1. argc函数中的main包含命令行参数的数量,包括脚本名称。因此,您不希望将第一个命令行参数解析为整数值。
  2. sizeof中的for(r = 0; r < sizeof(returnValue); r++)运算符为您提供了returnValue变量的字节数,在64位操作系统中它应该始终为8,因为它是一个指针值。使用其他方法来获取结果数组的大小。
  3. 你得到的警告是因为类型滥用。进行显式类型转换以修复它。
© www.soinside.com 2019 - 2024. All rights reserved.