lundi 29 novembre 2021

Thread separated random int generation in C++

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?




Aucun commentaire:

Enregistrer un commentaire