【问题标题】:How to fix "aggressive loop optimization" error with threads?如何使用线程修复“积极循环优化”错误?
【发布时间】: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&lt;=4; i++)。当i4 时,它将是thread 数组的无效索引。有效索引为 0-3。在 C 中,数组索引从 0 开始。所以应该是for (int i=0; i&lt;4; i++)
  • 您的代码可能使用线程,但它不会并行执行任何操作,这违背了使用线程的目的。此外,还有很多其他事情都关闭了。如果您有此运行,请考虑将其提交到 codereview.stackexchange.com 以供审核。
  • 你认为你为什么需要free(arg);

标签: c multithreading loops optimization pthreads


【解决方案1】:

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

你错过了用sumsum[0]的第一个元素的值来总结totalsumsum的所有元素的值。

同样适用:

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 指向不需要释放内存 - 由先前调用内存管理函数分配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多