gpt4 book ai didi

c++ - boost 随机和 OpenMP

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:25 25 4
gpt4 key购买 nike

我从代码的 OpenMP 并行部分收到“总线错误”。我在下面重新创建了一个简单版本的问题。该代码实质上对函数 uniform_distribution 进行了多次调用。 ,它使用 Boost 的 uniform_int_distribution 绘制一个 0 到 20000 之间的整数。

post警告两个线程访问同一个对象。我猜那是 eng就我而言。 (不幸的是,我不知道如何编写“合适的互斥包装器”,正如该帖子所建议的那样)。

我想到的一个可能的肮脏解决方案是创建一个本地 eng#pragma for里面循环并将其作为参数传递给 uniform_distribution .我不喜欢这个想法,因为在我的真实代码中,我调用了很多函数,并传递了一个本地 eng会很麻烦。另外,我担心的是,如果我声明 eng,不同的线程将生成相同 随机数序列。里面uniform_distribution .所以我有两个要求:如何并行化

  1. 每个线程都从其他线程生成概率独立的绘图?
  2. RNG 上没有出现竞争条件?

谢谢;非常感谢任何帮助。

#include <omp.h>
#include <boost/random/uniform_int_distribution.hpp>

boost::random::mt19937 eng;

int uniform_distribution(int rangeLow, int rangeHigh) {
boost::random::uniform_int_distribution<int> unirv(rangeLow, rangeHigh);
return unirv(eng);
}
int main()
{
# pragma omp parallel for private(eng)
for (int bb=0; bb<10000; bb++)
for (int i=0; i<20000; i++)
int a = uniform_distribution(0,20000);

return 0;
}

最佳答案

我认为最方便的解决方案是使用 thread_local RNG 和涉及线程 ID 作为每个线程的唯一编号的播种,例如,您可以在系统时间和线程 ID 之间执行 XOR 以播种 RNG。类似于(使用 C++11):

#include <omp.h>
#include <boost/random/uniform_int_distribution.hpp>

#include <thread>
#include <ctime>

boost::random::mt19937& get_rng_engine() {
thread_local boost::random::mt19937 eng(
reinterpret_cast<unsigned int>(std::time(NULL)) ^ std::this_thread::get_id());
return eng;
};

(注意:如果你打算使用 C++11,你也可以使用 <random>)

如果您不能使用 C++11,那么您可以使用 boost::thread相反,要有类似的行为,请参阅 thread-local storage 上的 Boost 页面也是。

关于c++ - boost 随机和 OpenMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15504264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com