【发布时间】:2018-03-05 04:22:01
【问题描述】:
我有这个项目,我从命令行接收输入,例如“54 342 12”,假设为每个输入创建一个线程并让线程返回一个整数数组,然后主线程应该打印出不同的素数分解。但是我收到了奇怪的输出,例如一堆零。我不知道为什么,任何帮助将不胜感激。
#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 = 1; 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 = 1; i < argc; ++i){
void *returnValue;
int r = 0;
int x = (sizeof(returnValue) / sizeof(returnValue[0])) - 1;
pthread_join(thr[i], &returnValue);
for(r = 0; r < x; r++){
//int c = (int *)returnValue[r];
printf("%d ", ((int *)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);
}
【问题讨论】:
-
欢迎来到 Stack Overflow!请阅读Why is “Can someone help me?” not an actual question?。寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括期望的行为、特定问题或错误以及重现它所需的最短代码问题本身。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。
-
你没有数组,你有一个指向分配内存的指针。
sizeof(returnValue)会给你 4 或 8,这取决于你的系统架构,不管它实际指向多少内存。您需要从命令行捕获大小并使用main中的大小循环访问内存。这会很好看:c-faq.com/aryptr/index.html