C “如何修复”;“积极循环优化”;线程出错?
我得到一个警告,“迭代3调用未定义的行为”。任务是:创建一个多线程程序,该程序从用户处读取整数值n(您可以假设任何常数),并使用4个新线程查找从1到n的数字之和,其中每个线程仅计算总和的¼。主线程打印出最终的总和 下面给出了我的代码,提前谢谢C “如何修复”;“积极循环优化”;线程出错?,c,multithreading,loops,optimization,pthreads,C,Multithreading,Loops,Optimization,Pthreads,我得到一个警告,“迭代3调用未定义的行为”。任务是:创建一个多线程程序,该程序从用户处读取整数值n(您可以假设任何常数),并使用4个新线程查找从1到n的数字之和,其中每个线程仅计算总和的¼。主线程打印出最终的总和 下面给出了我的代码,提前谢谢 //gcc 5.4.0 #include <pthread.h> //pthread_t #include <stdlib.h> #include <unistd.h> #include <stdio.h>
//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;
}
//gcc 5.4.0
#包括//pthread\t
#包括
#包括
#包括
浮点数[5];
void*sumf(void*arg){
int a=*((int*)arg);
for(int i=1;ipthread\u t thread[4];
-thread
是包含4个元素的pthread\u t
数组
使用时:
for (int i = 1; i <= 4; i++){
pthread_create(&thread[i], NULL, sumf, (void *)np);
pthread_join(thread[i], NULL); //thread waits
}
for(int i = 1; i <= 4; i++){
totalsum += sum[i];
}
您没有使用sum
的第一个元素的值,sum[0]
来汇总totalsum
中sum
的所有元素的值
这同样适用于:
for(int i = 1; i <= 4; i++){
sum[i] = a + a * (a/8); // Using arithmetic sequence formula to find 1/4 part of sum
}
<代码> >(int i=1;i <代码> pthRead)线程(4);(int i=1);您的代码可以使用线程,但它不能并行执行任何操作,这就违背了使用线程的目的。此外,还有很多其他事情被关闭。如果您有此运行,请考虑在CODReVIEW.STACKExchange .COM中提交它。您认为为什么需要<代码>免费(ARG)?;
?
for (int i = 1; i <= 4; i++){
pthread_create(&thread[i], NULL, sumf, (void *)np);
pthread_join(thread[i], NULL); //thread waits
}
for (int i = 0; i < 4; i++){
pthread_create(&thread[i], NULL, sumf, (void *)np);
pthread_join(thread[i], NULL); //thread waits
}
for(int i = 1; i <= 4; i++){
totalsum += sum[i];
}
for(int i = 0; i <= 4; i++){
totalsum += sum[i];
}
for(int i = 0; i < 5; i++){
totalsum += sum[i];
}
for(int i = 1; i <= 4 ; i++){
sum[i] = a + a * (a/8); // Using arithmetic sequence formula to find 1/4 part of sum
}
for(int i = 0; i <= 4; i++){
sum[i] = a + a *(a/8); // Using arithmetic sequence formula to find 1/4 part of sum
}
for(int i = 0; i < 5; i++){
sum[i] = a + a * (a/8); // Using arithmetic sequence formula to find 1/4 part of sum
}