C ++ 11 threads do not change the same values

I am writing a program that (ideally) requires two threads to start simultaneously.

I have a global vector variable myObjects to track my objects:

vector<Object> myObjects;

And an object of the type MoNDthat will perform heavy lifting. It is initialized by the vector as an argument, and it pushes the "objects" into the vector. There are no problems so far.

MoND  mySim =  MoND(myObjects);

Basically, the mySim method should be called with myObjectsas an argument. In the non-streaming version that I used for testing, this works (start crashing after 100 iterations):

int main(int argc, char** argv) {
  ...
  mySim.Run(myObjects);// Run simulation on Objects
  glutMainLoop();      // Enter the event-processing loop                                                                                            
  return 0;
}

For work, I mean changing the properties Objectstored in myObjects. It is necessary to constantly and simultaneously work, so that it is not ideal.

Using streams:

int main(int argc, char** argv) {
  ...
  thread t1(&MoND::Run, mySim, myObjects);// Run simulation on Objects
  glutMainLoop();      // Enter the event-processing loop                                                                                            
  return 0;
}

. Run() myObjects , myObjects, . myObjects ? (, , )

, , ( , , ). , , , .

myObjects (.. )?

:

  • , , , ( / )

  • Run() Object SetPos(args..) SetVel(args..)

+4
2

std::thread , , , .

, std::ref:

thread t1(&MoND::Run, mySim, std::ref(myObjects));

, .

std::bind std::async .

, mySim , , .

+10

, , , : .

.

0

Source: https://habr.com/ru/post/1544380/


All Articles