Using random_device in classes [closed]

孤街浪徒 提交于 2021-02-08 06:10:09

问题


What part of this code would be logical to call in your main{} class, and what part should be used within (for instance) the constructor of a new object (what should I pass as argument(s)), and why? The question is more along the lines of, what is the best way of passing random_device variables to objects (arguments, etc)?

srand ( time ( NULL ) );
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, 10);

for (int i=0; i<40; ++i)
    std::cout << (int)dist(mt) << " ";
std::cout << endl;

回答1:


If you are asking how to make the pseudo random number generator object available to all classes, you can use an externally defined global variable (like std::cout), or depending on your needs, a global in anonymous namespace, or a singleton.

However the safest and easiest method I found so far is to create one instance per thread. Here's how I do it:

std::mt19937 &mt()
{
  // initialize once per thread
  thread_local static std::random_device srd;
  thread_local static std::mt19937 smt(srd());
  return smt;  
}

Now each thread has its own random number generator.

Note: for visual studio, you can try using boost's thread_specific_ptr or wrap the random_device and mersenne twister in a class and use visual c++ TLS.



来源:https://stackoverflow.com/questions/21328048/using-random-device-in-classes

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