GCC 8.1.0/MinGW64 编译的 OpenMP 程序崩溃寻找 cygwin.s?

GCC 8.1.0/MinGW64-compiled OpenMP program crashes looking for cygwin.s?

感谢您对 rand() 和线程安全的提醒。我最终用一些在 OpenMP 中似乎运行良好的代码替换了我的 RNG 代码,这在视觉上简直是天壤之别。我会尝试其他更改并报告。谢谢!

哇!它运行 快得多 并且图像没有伪影!谢谢!

贾丹布利斯

最终代码:

#pragma omp parellel
for (j = options.height - 1; j >= 0; j--){
    for (i=0; i < options.width; i++) {
            #pragma omp parallel for reduction(Vector3Add:col)
            for (int s=0; s < options.samples; s++)
            {
                float u = (float(i) + scene_drand()) / float(options.width);
                float v = (float(j) + scene_drand()) / float(options.height);
                Ray r = cam.get_ray(u, v); // was: origin, lower_left_corner + u*horizontal + v*vertical);

                col +=  color(r, world, 0);
            }

            col /= real(options.samples);
            render.set(i,j, col);
            col = Vector3(0.0);
    }
}

错误:

Starting program: C:\Users\Jadan\Documents\CBProjects\learnOMP\bin\Debug\learnOMP.exe [New Thread 22136.0x6620] [New Thread 22136.0x80a8] [New Thread 22136.0x8008] [New Thread 22136.0x5428]

Thread 1 received signal SIGSEGV, Segmentation fault. ___chkstk_ms () at ../../../../../src/gcc-8.1.0/libgcc/config/i386/cygwin.S:126 126
../../../../../src/gcc-8.1.0/libgcc/config/i386/cygwin.S: No such file or directory.

以下是对您的代码的一些评论。

使用大量线程不会给您带来任何好处,这可能是您出现问题的原因。线程创建具有时间和资源成本。时间成本使得它可能是您程序中的主要时间,并且您的并行程序将比其顺序版本长得多。关于资源成本,每个线程都有自己的堆栈段。它的大小取决于系统,但典型值以 MB 为单位。我不知道你的系统的特性,但是有 100000 个线程,这可能是你的代码崩溃的原因。我无法解释有关 cygwin.s 的消息,但在堆栈溢出后,行为可能很奇怪。

线程是并行化代码的一种手段,并且对于数据并行化,大多数情况下线程数量多于系统上逻辑处理器的数量是无用的。让 openmp 设置它,但您可以稍后尝试调整此数字。

除此之外,还有其他问题

rand() 不是 thread safe,因为它使用将由线程同时修改的全局状态。 rand_r() 是,因为随机生成器的状态不是全局的,可以存储在每个线程中。

你不应该在没有 atomic 访问的情况下修改像 result 这样的共享变量,因为并发线程访问会导致意外结果。虽然安全,但对每个值使用原子修改并不是一个非常有效的解决方案。原子访问非常昂贵,最好使用在每个线程中进行本地累加的缩减,并在最后使用唯一的原子访问。

#include <omp.h>
#include <iostream>
#include <random>
#include <time.h>

int main()
{
    int runs = 100000;
    double result = 0.0;
#pragma omp parallel
    {
      // per thread initialisation of rand_r seed.
      unsigned int rand_state=omp_get_thread_num()*time(NULL);
                     // or whatever thread dependent seed
#pragma omp for reduction(+:result)
      for(int i=0; i<runs; i++) 
        {
          double d = double(rand_r(&rand_state))/double(RAND_MAX);
          result += d;
        }
    }
    result /= double(runs);
    std::cout << "The computed average over " << runs << " runs was " 
           << result << std::endl;
    return 0;
}