N0rA
N0rA

Reputation: 612

Thread safe random numbers

I tried to implement "Monte Carlo" algorithm in parallel manner, so I need to use a thread safe version of a random number generator.
I searched a lot and finally found int qrand () which is a Thread-safe version of the standard C++ rand() function, (defined in <cstdlib> and <stdlib.h>). When I use it, VS fired "identifier not found" error.

I use MS visual studio'10 and wrote my code in C++ using OMP.

Any help?

Upvotes: 1

Views: 4870

Answers (2)

bames53
bames53

Reputation: 88155

For C++ use the standard <random> library. As James Kanze suggests, a different generator for each thread would probably be best, and they're not difficult to make:

#include <random>

std::mt19937 make_seeded_engine() {
    std::random_device r;
    std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
    return std::mt19937(seed);
}

std::async([](){
    auto rand = std::bind(std::uniform_real_distribution<>(),
                          make_seeded_engine());
    for(int i = 0; i < 100; ++i)
        rand();
});

I'm just using std::async() to show that the generator is created in the thread. MSVC 10 doesn't have std::async() I don't think, but it does have <random>, so you'll do the same thing just using whatever threading library you're already using.

Upvotes: 6

James Kanze
James Kanze

Reputation: 153909

boost::random has a number of generators which are objects. The simplest solution would be to simply use a distinct generator for each thread.

Upvotes: 3

Related Questions