Home > database >  Thread separated random int generation in C
Thread separated random int generation in C

Time:11-30

I need to genetate three .txt files filled with random int, calling the generate function in sepatared threads.

The problem is that as a result I have the same values in every .txt files.

A function that gererates and writes values:


        void generateMoves(int limit, std::string outputPath) {
        //open fstream
        std::ofstream fout;
        fout.open(outputPath);
        if (!fout.is_open()) {
            std::cout << "Error reading " << outputPath << " file. Exiting..." << std::endl;
            exit(1);
        }
    
        static thread_local std::mt19937 generator;
        std::uniform_int_distribution<int> distribution(1, 3);
    
        //generating & writing moves
        for (int i = 0; i < limit; i  ) {
            
            int value;
            value = distribution(generator);
            fout << value << std::endl;
        }
    
        fout.close();
    }

I call threads like this from main():

    int limit = 1000;
    std::thread player1(generateMoves, limit, "player1.txt");
    std::thread player2(generateMoves, limit, "player2.txt");
    std::thread player3(generateMoves, limit, "player3.txt");

    player1.join();
    player2.join();
    player3.join();

So, how do I separate int generation correctly?

Edit: Following the comment below, I putted diffent seed into each thread and everything works fine now. The random generation looks like this now:

    // put different *s* into each thread
    srand(s);
    //generating & writing
    for (int i = 0; i < limit; i  ) {
        int value;
        value = rand() % 3   1;
        fout << value << std::endl;
    }

CodePudding user response:

As the comments state, all your generators have been created from the same default seed. It suffices to give each generator a different seed:

std::random_device rd1;
static thread_local std::mt19937 generator(rd1());

This uses the (very slow) std::random_device, but only to generate a unique seed for the mt generator.

  • Related