gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:34:59 24 4
gpt4 key购买 nike

我正在尝试找出多个数字的质因数分解。如果用户输入 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);
}

最佳答案

您在代码片段中犯了一些错误。

  1. argcmain函数包含命令行参数的数量,包括脚本名称。因此您不想将第一个命令行参数解析为整数值。
  2. sizeof for(r = 0; r < sizeof(returnValue); r++) 中的运算符给出 returnValue 的字节数变量,在 64 位操作系统中应始终为 8,因为它是指针值。使用其他方法来获取结果数组的大小。
  3. 您收到的警告是由于类型误用造成的。进行显式类型转换来修复它。

关于c - POSIX 返回并打印数组 prthread_join()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49102757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com