My program needs to generate many random integers in some range (int min, int max). Each call will have a different range. What is a good (preferably thread-safe) w
I am a person from the future with the same problem. The accepted answer won't compile on MSVC 2013, because it doesn't implement thread_local (and using __declspec(thread)
doesn't work because it doesn't like constructors).
The memory leak in your solution can be moved off the heap by modifying everything to use placement new.
Here's my solution (combined from a header and source file):
#ifndef BUILD_COMPILER_MSVC
thread_local std::mt19937 _generator;
#else
__declspec(thread) char _generator_backing[sizeof(std::mt19937)];
__declspec(thread) std::mt19937* _generator;
#endif
template inline type_float get_uniform(void) {
std::uniform_real_distribution distribution;
#ifdef BUILD_COMPILER_MSVC
static __declspec(thread) bool inited = false;
if (!inited) {
_generator = new(_generator_backing) std::mt19937();
inited = true;
}
return distribution(*_generator);
#else
return distribution(_generator);
#endif
}