I am trying to write a simple random utility function with a static generator and distribution. All functions and variables are static and therfore shared across the program. My program is not currently using threads but I would like it to be able to later. Therfore I want to declear my generator as a thread_local
variable for performance reason.
I am trying to write a simple random utility function with a static generator and distribution. I want these variables to be thread_local, which works fine when compiling with gcc. With clang however, the program gives a seg fault when initializing the generator.
hpp file:
class Random
{
public:
Random() = delete;
static void initialize();
private:
thread_local static std::mt19937 s_generator;
thread_local static std::uniform_real_distribution<double> s_distribution;
};
cpp file:
thread_local std::mt19937 Random::s_generator{};
thread_local std::uniform_real_distribution<double> Random::s_distribution{0.0, 1.0};
void Random::initialize()
{
s_generator.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
}
The line that seg fault is this s_generator.seed(...)
function. Now I know using the current time for seeding is a dubious idea at best, but it works fine for my application for now and other types of seeds also gives a seg fault. I found a SO post saying the variables need to pass through main to be initialized, but global variables instead initializes their own copies. So i tried having them as global variables, but with the same result for clang. I have also had problems with thread_local
variables in other external libraries in my code
My questions are: Is there a bug with clang and thread_local
? Is the code provided something that should work? If not what can be changed. Are there any compiler flags or other things that may fix the problem?
Thanks is advance