std :: random_device的线程安全 [英] Thread safety of std::random_device

查看:383
本文介绍了std :: random_device的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的代码:

I have some code which looks a bit like this:

std::random_device rd;

#pragma omp parallel
{
    std::mt19937 gen(rd());
    #pragma omp for
    for(int i=0; i < N; i++)
    {
        /* Do stuff with random numbers from gen() */
    }
}

我有几个问题:

  • std::random_device线程安全吗?即当几个线程一次调用它会做一些无益的事情吗?
  • 这通常是个好主意吗?我应该担心随机数流重叠吗?
  • 是否有更好的方法来实现我想要的功能(每个线程中的独立随机数流-我现在不太担心可重复性)?
  • Is std::random_device thread safe? i.e. Is it going to do something unhelpful when several threads call it at once?
  • Is this generally a good idea? Should I be worried about overlapping random number streams?
  • Is there a better way to achieve what I want (independent random number streams in each thread - I'm not too worried about reproducibility at the moment)?

如果它与std::random_device的工作方式有所不同,我主要在Windows上运行,尽管我希望代码在Linux和OSX上也能正常工作.

In case it make any difference to the workings of std::random_device I'm primarily running on Windows, though I would like the code to work equally well on Linux and OSX as well.

推荐答案

并行使用随机设备不是一个好主意.即使阻塞,您可能也不会遇到重叠的随机数流的麻烦,但是您可以添加一个额外的同步点.

It's not a good idea to use the random device in parallel. Even if it's blocking you may not have troubles with overlapping random number streams but you add a additional synchronization point.

您应该设置与要启动的线程一样多的随机数引擎(RNE), omp_get_num_threads() . 创建RNE的std :: vector并将它们植入程序的顺序部分.对于播种,您可以使用随机设备和 std :: seed_seq

You should set up as many random number engines (RNE) as many threads you want to start, omp_get_num_threads(). Create an std::vector of RNEs and seed them in the sequential part of your program. For seeding you can use the random device and a std::seed_seq.

然后在每个线程中使用与线程号 omp_get_thread_num() 关联的RNE.

Then use in each thread the RNE associated with with the thread number, omp_get_thread_num().

从不使用随机设备生成随机数,它的速度很慢,并且通常不会生成均匀分布的随机数!

Never use the random device to generate random numbers, its's slow and in general not generating uniformly distributed random numbers!

根据所需的随机数质量,可以使用预定义的随机数生成器之一.如果您要进行蒙特卡洛模拟或密码学,请特别小心选择哪种算法.

Depending on the quality of the random numbers you need you can use one of the predefined random number generators. If you are doing Monte Carlo simulations or Cryptography be extra careful what algorithm you choose.

您会发现有关随机引擎的许多有用信息,网址为 https://en.cppreference.com/w/cpp/numeric/random.

You'll find a lot useful information on random engines at https://en.cppreference.com/w/cpp/numeric/random.

这篇关于std :: random_device的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆