lundi 16 mars 2020

C++ thread safe vector insertion

Multiple threads process data and at the end they all insert/append results in RESULT vector.
I want to make sure that only one thread insert elements in RESULT vector at a time.
For that I have used mutex and lock_guard() but they are giving invalid access error sometimes and sometimes they don't...
Here is my code to synchronize

void insert_output() {
    mutex m;
    lock_guard<mutex> lockGuard(m);
    Resources::results.insert(Resources::results.begin(), output.begin(), output.end());
}

Am I doing something wrong...
And what is better way to synchronize this process ?

Aucun commentaire:

Enregistrer un commentaire