我想将 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/