lundi 15 août 2016

How to make reproducible random number generation with parallel threads?

I have two random number functions, that are defined in common.h like this:

static std::default_random_engine eng12(MAINSEED);//linear

static std::uniform_real_distribution<float> fdis12(0.0, 1.0);
inline float getRandf(){
    return fdis12(eng12);
}

static uint32_t x123(100), y123(134), z123(321), w123(25);

inline uint32_t getRandi(void) {
    uint32_t t = x123 ^ (x123 << 11);
    x123 = y123; y123 = z123; z123 = w123;
    return w123 = w123 ^ (w123 >> 19) ^ t ^ (t >> 8);
}

How can I use them in reproducible manner? I set seeds, but when it goes into parallel processing, as I understand it, objects get processed in random sequence and every time it's different. Also I'm not sure about thread safety,I mean, can I use these two functions in parallel at all? If I can't, what should I change?

I use them in several different cpp files. Then I do something like this:

1.h
#include "common.h"
1.cpp
struct Obj{
   float f;
   void mutate(){
     f = getRandf();
   }
};
2.h
#include "common.h"
2.cpp
void doInParallel(Obj* obj, int idStart, int idEnd){
    for(int i = idStart; i < idEnd; i++){
        int x = getRandi()%10;
        //do something with x;
        obj[i].mutate();
    }
}

Am I doing this right at all? I'm not very experienced. I use a different one for int because it's faster(24 times faster) than randf and I don't need that good random with randi anyway.




Aucun commentaire:

Enregistrer un commentaire