boost - 将 boost 随机数生成器与 OpenMP 结合使用

标签 boost random numbers generator openmp

我想将 C++ 中的 boost 随机数生成器代码与 OpenMP 并行化。我想以既高效又线程安全的方式做到这一点。有人可以指导我如何完成此操作吗?我目前附上以下内容;这显然不是线程安全的,因为 SampleNormal 函数中的静态变量可能会给出 竞争条件。样本数(nsamples)远大于n。

#pragma omp parallel for private(i,j) 
for (i = 0; i < nsamples; i++) {
   for (j = 0; j < n; j++) {
      randomMatrix[i + nsamples*j] = SampleNormal(0.0, 1.0);
   }
}

double SampleNormal (double mean, double sigma)
{
  // Create a Mersenne twister random number generator
  static mt19937 rng(static_cast<unsigned> (std::time(0)));
  // select Gaussian probability distribution
  normal_distribution<double> norm_dist(mean, sigma);
  // bind random number generator to distribution
  variate_generator<mt19937&, normal_distribution<double> >  normal_sampler(rng, norm_dist);
  // sample from the distribution
  return normal_sampler();
}

最佳答案

您只需要线程安全的东西还是可扩展的东西?如果您的 PRNG 不需要非常高的性能,您可以在 rng 对象的使用周围加一个锁。为了获得更高的性能,您需要找到或编写一个并行伪随机数生成器--http://www.cs.berkeley.edu/~mhoemmen/cs194/Tutorials/prng.pdf有关于它们的教程。一种选择是将您的 mt19937 对象放入线程本地存储中,确保使用不同的种子为不同的线程提供种子;这使得在不同的运行中重现相同的结果变得困难,如果这对您很重要的话。

关于boost - 将 boost 随机数生成器与 OpenMP 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405526/

相关文章:

C++:使用 boost::regex 将管道分隔的字符串与通配符匹配

c++ - 我如何将 "prepare "字符数组转换为 boost::asio::streambuf::mutable_buffers_type 缓冲区?

boost asio channel "no type named ' receive_cancelled_signature'"

python - Boost Python,Visual Studio 链接到错误的 boost dll

string - GoLang 获取 byte slice 中第 N 行的字符串

random - 从时间戳生成确定性随机数

random - 在偏向中间的范围内生成随机无符号整数

javascript - 在字符串前加零

vector - 如何将文件中的数字列表读入 Vec?

javascript - 将字符串转换为整数 BigInt