lundi 8 octobre 2018

Member variables changing on their own when multithreading c++

This is my first attempt at multithreading my code.

The code consists of a class Simulation that creates individual Simulation objects. Since I need to run several of them I wanted to run them in parallel across multiple threads. The code works perfectly fine in serial but when assigning each simulation object method to a different thread I encounter segmentation faults at different times (usually very early on) which I assume is due to some kind of data racing happening. Digging a bit deeper I found that some member variables seem to get reinitialised or just change values (not consistently in every run). It is clear to me that some resources are getting mixed up but how can that happen when I am running each simulation in an independent thread (or so I think)?

Heres a simplified version of the code.

Simulation class:

   class Simulation{
    public:
    void run(){
        //Complicated stuff;                    
       }
    };

main.cpp:

int main(){
        vector<Simulation> simulations;
        vector<thread> threads;

    for (int i=0; i<nSimulations; i++){
        simulations.push_back(
            Simulation(params));
        threads.push_back(thread(&Simulation::run,
            std::ref(simulations[i])));
    }

    for (int i=0; i<nSimulations; i++){
        threads[i].join();
        simulations[i].saveToFile("test.dat");
    }

return 0;
}

Is there anything inherently wrong with this piece of code? The actual code is quite complicated so at least I would like to know if this is the right way to multithread different object methods to different threads.

Aucun commentaire:

Enregistrer un commentaire