1

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?

Bart
  • 19,692
  • 7
  • 68
  • 77
N0rA
  • 612
  • 1
  • 7
  • 27
  • 1
    You might be interested in this question http://stackoverflow.com/questions/8285067/c-super-fast-thread-safe-rand-function –  Mar 07 '12 at 18:22
  • 1
    I think `qrand` is part of Qt, not standard C++. Maybe you're looking for `rand_r`? – Fred Larson Mar 07 '12 at 18:34
  • See http://stackoverflow.com/a/7114482/5987 particularly the part about concurrency. – Mark Ransom Mar 07 '12 at 18:38
  • If you're using MSVC, the standard C/C++ `rand()` *is* threadsafe since the seed is stored in TLS (at least since VS2005), not sure it's the best solution though since the distribution of `rand()` isn't very random... – Andreas Magnusson Mar 07 '12 at 20:45

2 Answers2

6

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.

bames53
  • 86,085
  • 15
  • 179
  • 244
3

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

James Kanze
  • 150,581
  • 18
  • 184
  • 329