c - C 错误输出中的简单 OpenMP For 循环

标签 c multithreading openmp

试图让一个简单的 OpenMP 循环运行,但我不断收到奇怪的输出。它没有直接从 1 到 1000 列出,而是从 501 到 750,然后从 1 到 1000。我猜这是线程问题?我正在 VS2013 上编译和运行。

#include <stdio.h>
#include <math.h>

int main(void)
{
    int counter = 0;
    double root = 0;

    // OPEN MP SECTION
    printf("Open MP section: \n\n");
    getchar(); //Pause

#pragma omp parallel for 

    for (counter = 0; counter <= 1000; counter++)
    {
        root = sqrt(counter);
        printf("The root of %d is %.2f\n", counter, root);

    }


    return(0);


} 

最佳答案

OpenMP 的全部是并行运行,将工作分配给不同的执行引擎。

因此,循环的各个迭代很可能是无序完成的,因为这是多线程的本质。

虽然并行进行计算可能有意义(因此可能会乱序),但这并不是您真正想要的打印结果.

确保以正确顺序打印结果的一种方法是将打印推迟到并行执行完成之后。换句话说,并行化计算但串行化输出。

这当然意味着能够在并行操作运行时将信息存储在例如数组中。

换句话说,像这样:

// Make array instead of single value.

double root[1001];

// Parallelise just the calculation bit.

#pragma omp parallel for 
for (counter = 0; counter <= 1000; counter++)
    root[counter] = sqrt(counter);

// Leave the output as a serial operation,
//   once all parallel operations are done.

for (counter = 0; counter <= 1000; counter++)
    printf("The root of %d is %.2f\n", counter, root[counter]);

关于c - C 错误输出中的简单 OpenMP For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27762711/

相关文章:

c++ - GCC 4.8.2 中缺少 OpenMP 4 功能

c - 是否定义了负 bool 值?

c - Objective C 版本的 explode()?

c++ - ACE 互斥体如何工作以及为什么 ACE 线程互斥体的工作方式不同?

c# - 不同线程中的渲染控制

synchronization - OpenMP 命名的关键部分 : if a program variable is used, 是被评估还是被用作字符串而不被评估?

c - pread() 中的奇怪行为?

c - 当我在简单的 C 程序中返回值时,我没有收到任何消息。我该如何解决这个问题?

java - 多线程同步问题

c++ - OpenMP 和 STL vector