且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使每个线程在C ++ 11中使用自己的RNG

更新时间:2021-12-10 23:17:15

您不能在多个线程之间共享随机引擎的实例。你应该锁定单个引擎或为每个线程创建一个引擎(具有不同的种子(请注意e4e5f4关于创建并行MT引擎的答案))。在OpenMP的情况下,你可以轻松地在一个向量中存储一个引擎,并通过 omp_get_thread_num()的结果检索它,它在0和 omp_get_num_threads )-1

You must no share instances of random engine between multiple threads. You should either lock a single engine or create one engine for each thread (with different seed (please note the answer of e4e5f4 regarding creation of parallel MT engines)). In case of OpenMP you can easily store one engine per thread in a vector and retrieve it by result of omp_get_thread_num() which lies between 0 and omp_get_num_threads()–1.

class RNG
{
public:
    typedef std::mt19937 Engine;
    typedef std::uniform_real_distribution<double> Distribution;

    RNG() : engines(), distribution(0.0, 1.0)
    {
        int threads = std::max(1, omp_get_max_threads());
        for(int seed = 0; seed < threads; ++seed)
        {
            engines.push_back(Engine(seed));
        }
    }

    double operator()()
    {
        int id = omp_get_thread_num();
        return distribution(engines[id]);
    }

    std::vector<Engine> engines;
    Distribution distribution;
};

int main()
{
     RNG rand;
     unsigned long app = 0;

     #pragma omp parallel for reduction(+:app)
     for (unsigned long long i = 0; i < 2000000000; i++)
     {
         if(rand() < 0.5) app++;
     }
}