Thread safety of std::random_device

∥☆過路亽.° 提交于 2019-12-04 22:52:17

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.

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!