On 10/12/2019 2:14 PM, Manfred wrote:
> On 10/12/2019 9:58 PM, Chris M. Thomasson wrote:
>> On 10/12/2019 12:40 AM, Bonita Montero wrote:
>>>
>>> Is there any guarantee the standard makes that random_device shoudn't
>>> start at the same internal state for all new threads, i.e. the output
>>> of the following code is likey to be different on both lines?
>>
>> I don' think so, however, the term non-deterministic is used:
>>
>>
https://en.cppreference.com/w/cpp/numeric/random/random_device
>>
>> A random device per thread should be okay. Although, one can create a
>> PRNG per thread and use a single random device to gain their
>> individual per-thread seeds.
>
> The page also says that "In this case [PRNG] each std::random_device
> object may generate the same number sequence."
>
> Bottom line is that the properties random_device are implementation
> dependent, so the authoritative source is the implementation, rather
> than the standard.
Agreed. I think a per-thread PRNG seeded with a std::random_device is
fine. The thread would take the seed from a single instance of
std::random_device at startup, before passing control to the user. It
can even mix in its thread id for the seed as an experiment. Therefore,
after this, a thread can use its own per-thread context to generate a
pseudo random number without using any sync.
basic pseudo-code, abstract on certain things:
struct rnd_dev
{
a_true_random_ng rdev; // assuming a non-thread safe TRNG
std::mutex mtx;
seed_type generate()
{
mtx.lock();
seed_type seed = rdev.generate();
mtx.unlock();
return seed;
}
};
static rnd_dev g_rnd_dev;
struct per_thread
{
prng rseq; // thread local prng
void startup()
{
// seed with the main TRNG
rseq.seed(g_rnd_dev.generate());
}
// generate a thread local PRN
rnd_type generate()
{
return rseq.next();
}
};
Just for fun, Actually, each thread can use different PRNG algorithms. I
remember doing an experiment where there was a global static table of
function pointers to different PRNGS and a thread could choose between them.
Btw, can this be an implementation of a random device wrt its output:
https://groups.google.com/d/topic/comp.lang.c++/7u_rLgQe86k/discussion
;^)