如何修复线程的 "aggressive loop optimization" 错误?

How to fix "aggressive loop optimization" error with threads?

我收到警告“迭代 3 调用未定义的行为”。任务是:创建一个多线程程序,从用户那里读取一个整数值 n(你可以假设任何常数),并使用 4 个新线程计算从 1 到 n 的数字之和,其中每个线程只计算和的 ¼ .主线程打印出最后的总和。

下面给出了我的代码,先谢谢了

//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]; - thread 是一个包含 4 个元素的 pthread_t 数组。

使用时:

for (int i = 1; i <= 4; i++){
    pthread_create(&thread[i], NULL, sumf, (void *)np);  
    pthread_join(thread[i], NULL); //thread waits
}

程序在最后一次迭代中尝试访问超出数组边界的元素,因为索引从 0 开始,而不是 1。表示 thread 的最后一个元素是 thread[3],而不是 thread[4]。当 i == 4.

时,您尝试访问不存在的 thread[4]

还有使用时:

for(int i = 1; i <= 4; i++){
    totalsum += sum[i];
}

你错过了用sum的第一个元素的值,sum[0]来汇总totalsumsum的所有元素的值。[=37] =]

同样适用于:

for(int i = 1; i <= 4; i++){
     sum[i] = a + a * (a/8); // Using arithmetic sequence formula to find 1/4 part of sum
}

变化:

1.

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
}

2.

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];
}

3.

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
}

您也在使用 free(arg);,但这样做毫无意义。

arg 指向不需要释放的内存 - 由先前调用内存管理函数分配。