I’d like to multithread my rng part of my code using C++11.
I create a bunch of RNG’s like this:
typedef std::mt19937 mersenne_twister;
typedef std::uniform_real_distribution<double> unidist;
// 8 rng engines with 8 consecutive seeds
const size_t Nrng = 8;
const array<uint32_t,Nrng> seed_values = {0,1,2,3,4,5,6,7};
array<mersenne_twister,Nrng> engines;
const array<unidist,Nrng> distributions; // default constructor is for [0,1] interval
const array<????,Nrng> rngs; // What type do I put here?
for( size_t i=0; i<Nrng; ++i )
engines[i].seed(seed_values[i]);
rngs[i] = std::bind(distributions[i], engines[i]);
With the idea I can later pass each of the RNG objects to a seperate std::thread that fills another array with some form of random numbers using the supplied generator. I don’t know what type I need to use for the rng array. I know how to create one rng, like so:
auto rng = std::bind(unidist, generator);
but I need to explicitely have a (decltyped?) type for the array.
One possible type would be
std::function<double()>, but note that this doesn’t come free. The actual type of the result ofbindis unknowable, and so you cannot just make a container with element typedecltype(std::bind(...)), since the types are not guaranteed to be mutually convertible — all you know is that they all convert tofunction.If this is performance-critical, I suggest you profile and compare the cost of
std::functionto the direct use ofunidist(rngs[i])in your target code. (The distribution is a stateless adapter that should be reentrant anyway, so you don’t need to keep more than one copy of it.)