I currently have a code which works well, but I am learning C++, and hence would like to rid myself of any newbie mistakes. Basically the code is
vector<vector<float>> gAbs; void functionThatAddsEntryTogAbs(){ ... gAbs.pushback(value); } int main(){ thread thread1 = thread(functionThatAddsEntryTogAbs,args); thread thread2 = thread(functionThatAddsEntryTogAbs,args); thread1.join(); thread2.join(); std::sort(gAbs.begin(),gAbs.end()); writeDataToFile(gAbs,"filename.dat"); } For instance I remember learning that there are only a few instances where global variables are the right choice. My initial thought was just to have the threads write to the file, but then I cannot guarantee that the data is sorted (which I need), which is my I use std::sort. Are there any suggestions of how to improve this, and what are some alternatives that the more experiences programmers would use instead?
The code needs to be as fast as possible.
Thanks in advance
functionThatAddsEntryTogAbsdoes more than just adding an entry (computes something before), I would advise you to take a look at Mutexes. These are basically locks, and you could simply acquire it just before the insertion, and unlock it afterwards, to still allow the computation to be done in multiple threads