Are all <random> distributions threads safe, even though they are not constants?

Note that std :: normal_distribution :: operator () is not const and does not behave with const. (Some other distributions have () operators that behave in const, but are also not defined as const).

Given that std :: normal_distribution :: operator () is not a constant, is it possible to use the same normal_distribution object for multiple threads? Is this safe for all distributions in a random header?

Edit: That is, the next member function throws an error due to the const function, but using the operator (), which can change d. Is it always safe to fix this by declaring d mutable?

 class MyClass { public: MyClass::MyClass(double mu, double sigma) { d = normal_distribution<double>(mu, sigma); } double MyClass::foo(std::mt19937_64 & generator) const { return d(generator); } private: std::normal_distribution<double> d; } 
+5
source share
1 answer

No, such objects are not thread safe (like any other standard library object, unless otherwise indicated). You should not share any of these objects between threads without protecting them with a mutex or similar construct.

+7
source

Source: https://habr.com/ru/post/1271282/


All Articles