Home > Net >  Can I edit a global vector using multiple threads in C ?
Can I edit a global vector using multiple threads in C ?

Time:06-14

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

CodePudding user response:

You can access and modify global resources, including containers from different threads, but you have to protect them from doing that at the same time. Some exceptions are: no modifications are possible, the container itself is not changed and the threads are working on separate entries.

In your code, entries are added to the container, so you need mutexes, but by doing that your parallel code probably doesn't gain you much in speed. A better way could be to know how many entries need to be added, add empty entries (just initialize) and then assign ranges to the threads, so they can fill in the entries.

  • Related