Update zu Passing random generators around (functor) In jenen Beispiel habe ich den RNG per std::function übergeben. Das muss nicht sein. Mit std::function verliert man die inline Performance. Und es geht auch ohne seltsames std::bind.
Aktualisierter Code:
#include <random> #include <iostream> #include <functional> #include <omp.h> // can be passed by value. it has no state template<typename Function> int function2(Function dice) { int sum = 0; for(int i=0; i < 1000; i++) { sum += dice(); } return sum; } // pass by reference, it has state int function(std::minstd_rand& generator) { // we need random numbers from 0 to 10 std::uniform_int_distribution<int> distribution(0,10); // lambda instead of bind auto dice = [&](){ return distribution(generator); }; return function2(dice); } int main() { omp_set_num_threads(2); // create random generatores with random seed std::minstd_rand seedGen; std::minstd_rand generators[omp_get_num_threads()]; for(int i=0; i < omp_get_num_threads(); i++) { generators[i].seed(seedGen()); } #pragma omp parallel for for(int i=0; i < 8; i++) { const int id = omp_get_thread_num(); // pass one generator to our function int sum = function(generators[id]); std::cout << "Thread " << id << " sum " << sum << "\n"; } std::cout << "Info sizeof std::function<int()> " << sizeof(std::function<int()>) << "\n"; return 0; }