【发布时间】:2020-05-11 13:42:03
【问题描述】:
我的 C 程序有问题,我想我需要一些帮助。 我的程序正在使用多个线程进行一些计算。每个线程运行一个只有一个参数的方法,最后返回一个整数。
现在,为了完成我的计算,需要对所有子计算求和,即线程返回的所有整数的总和。
但不知何故,这个结果是不正确的。我认为我在从线程中获取所有返回的整数时犯了一个错误。 这是我的代码:
//creating the threads (with splitArray[] as an array of pointers to other arrays)
pthread_t threads[n];
for (int i = 0; i < n; i++) {
pthread_create(&threads[i], NULL, (void * )(countPrime), (void * )splitArray[i]);
}
//getting the results of the threads
int numPrimes = 0;
int save;
for (int i = 0; i < n; i++) {
pthread_join(threads[i],(void **) &save);
numPrimes = numPrimes + save;
}
这是每个线程的方法:
int countPrime(int array[]) {
int numPrimes = 0;
for (int i = 0; i < size; i++) {
//checking if array[i] is a prime number
if (isPrime(array[i])) {
numPrimes++;
}
}
return numPrimes;
}
我做错了吗?我是 C 新手,所以我对使用指针不是很有信心,这在这种情况下似乎是必要的。
非常感谢:)
【问题讨论】:
-
你真正从线程返回什么?请尝试创建minimal reproducible example 向我们展示。
-
Here is your answer 也可以查看here
-
什么是
splitArray?你得到什么结果?你期望的结果是什么?产生该结果的输入是什么?请花点时间刷新How to Ask 和this question checklist。
标签: c multithreading join return pthreads