0

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.

1
  • 2
    Do you really need to store the distributions? They're just little caller adapters with no state. You might as well just have a global unidist, and use unidist(rngs[i]) where needed.
    – Kerrek SB
    Jan 12, 2012 at 12:15

1 Answer 1

2

One possible type would be std::function<double()>, but note that this doesn't come free. The actual type of the result of bind is unknowable, and so you cannot just make a container with element type decltype(std::bind(...)), since the types are not guaranteed to be mutually convertible -- all you know is that they all convert to function.

If this is performance-critical, I suggest you profile and compare the cost of std::function to the direct use of unidist(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.)

1
  • Thanks for the useful answer. I'm going to make a global unidist variable and pass the mersenne_twister to my functions, generating random numbers by calling unidist(engine).
    – rubenvb
    Jan 12, 2012 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.