增强RNG的线程安全性

Mac*_*tka 4 c++ boost openmp boost-random

我有一个循环,应该通过insering一个openmp pragma很好地并行化:

  boost::normal_distribution<double> ddist(0, pow(retention, i - 1));
  boost::variate_generator<gen &, BOOST_TYPEOF(ddist)> dgen(rng, ddist);
  // Diamond                                                                
  const std::uint_fast32_t dno = 1 << i - 1;
// #pragma omp parallel for
  for (std::uint_fast32_t x = 0; x < dno; x++)
    for (std::uint_fast32_t y = 0; y < dno; y++)
      {
        const std::uint_fast32_t diff = size/dno;
        const std::uint_fast32_t x1 = x*diff, x2 = (x + 1)*diff;
        const std::uint_fast32_t y1 = y*diff, y2 = (y + 1)*diff;
        double avg =
          (arr[x1][y1] + arr[x1][y2] + arr[x2][y1] + arr[x2][y2])/4;
        arr[(x1 + x2)/2][(y1 + y2)/2] = avg + dgen();
      }
Run Code Online (Sandbox Code Playgroud)

(除非我发出错误,每次执行都不依赖于其他人.很抱歉,并非所有代码都被插入).

不过我的问题是 - 是否提升RNG线程安全性?它们似乎是指gcc的gcc代码,所以即使gcc代码是线程安全的,也可能不是其他平台的情况.

hka*_*ser 6

浏览Boost邮件列表档案可以:

Boost.Random不维护需要多线程保护的全局状态.

只要您不同时从两个线程访问任何给定对象,Boost.Random就是线程安全的.(访问两个不同的对象是可以的,只要它们不共享引擎).如果您需要这种安全性,使用适当的互斥包装器自行滚动它是微不足道的.

  • 换句话说,为每个线程创建一个rng? (5认同)