【发布时间】:2020-09-02 02:27:16
【问题描述】:
我收到警告,因为“第 3 次迭代调用未定义的行为”。任务是:创建一个多线程程序,从用户读取整数值 n(您可以假设任何常数)并使用 4 个新线程找到从 1 到 n 的数字之和,其中每个线程仅计算总和的 1/4 .主线程打印出最终的总和。
我的代码如下,提前谢谢
//gcc 5.4.0
#include <pthread.h> //pthread_t
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
float sum[5];
void *sumf(void *arg){
int a = *((int *) arg);
for(int i=1;i<=4; i++){
sum[i] = a+a*(a/8); // Using arithmetic sequence formula to find 1/4 part of sum
}
free(arg);
pthread_exit(0);
}
int main(void)
{
int n=4;
int *np=&n;
float totalsum=0;
pthread_t thread[4]; //declare threads
for (int i=1; i<=4; i++){
pthread_create(&thread[i], NULL, sumf, (void *)np);
pthread_join(thread[i], NULL); //thread waits
}
//main thread
for(int i=1; i<=4; i++){
totalsum+=sum[i];
}
printf("%.2f", totalsum);
return 0;
}
【问题讨论】:
-
pthread_t thread[4]; for (int i=1; i<=4; i++)。当i为4时,它将是thread数组的无效索引。有效索引为 0-3。在 C 中,数组索引从0开始。所以应该是for (int i=0; i<4; i++) -
您的代码可能使用线程,但它不会并行执行任何操作,这违背了使用线程的目的。此外,还有很多其他事情都关闭了。如果您有此运行,请考虑将其提交到 codereview.stackexchange.com 以供审核。
-
你认为你为什么需要
free(arg);?
标签: c multithreading loops optimization pthreads