Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all <random> distributions thread safe despite not being const?

Tags:

c++

random

c++11

Notice that std::normal_distribution::operator() is not const, nor does it behave in a const way. (Some other distributions have () operators that behave in a const way, but are also not defined to be const).

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

Edit: That is, the following member function throws an error due to the function being const but using the operator(), which can change d. Is it always safe to fix this by declaring d to be 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;
}
like image 799
PThomasCS Avatar asked Aug 27 '17 19:08

PThomasCS


1 Answers

No, such objects are not thread safe (as any other standard library object, unless otherwise specified). You shouldn't share any of those objects between threads without protecting them with a mutex or similar construct.

like image 125
Matteo Italia Avatar answered Sep 27 '22 20:09

Matteo Italia