尽管不是const,所有<random>分布都是安全的吗?

PTh*_*sCS 6 c++ random c++11

请注意,std :: normal_distribution :: operator()不是 const,也不是const方式.(其他一些发行版具有以const方式运行的()运算符,但也未定义为const).

鉴于std :: normal_distribution :: operator()不是const,在多个线程中使用相同的normal_distribution对象是否仍然安全?随机标题中的所有发行版都安全吗?

编辑:也就是说,以下成员函数抛出一个错误,因为函数是const但是使用operator(),它可以改变d.通过声明d是可变的来解决这个问题总是安全的吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*lia 8

不,这些对象不是线程安全的(与任何其他标准库对象一样,除非另有说明).您不应在线程之间共享任何这些对象,而不使用互斥锁或类似构造保护它们.