Std :: vector push_back does not work when used in parallel loop

I have code that is following (simplified code):

for( int i = 0; i < input.rows; i++ )
{
    if(IsGoodMatch(input[I])
    { 
        Newvalues newValues;
        newValues.x1=input.x1;
        newValues.x2=input.x1*2;
        output.push_back( newValues);
    }
} 

This code works well, but if I want to make it parallel using omp parallel for, I get an error on output.push_back, and it seems that the memory is corrupted when the vector changes.

What is the problem and how to fix it?

How can I make sure that only one thread inserts a new element into the vector at any time?

+4
source share
4 answers

std::vector push_back cannot guarantee the correct behavior when calling at the same time as it is now (there is no thread safety).

, , resize :

output.resize(input.rows);
int k = 0;

#pragma omp parallel for shared(k, input)
for( int i = 0; i < input.rows; i++ )
{
    if(IsGoodMatch(input[I])
    { 
        Newvalues newValues;
        ...
        // ! prevent other threads to modify k !
        output[k] = newValues;
        k++;
        // ! allow other threads to modify k again !
    }
} 

output.resize(k);

operator[] std::vector, . (.. , mutex), k.

" , ?"

. ( ). , , , .

+6

: std::vector::push_back .

, , , push_back .

++ 11 std::mutex.

+6

#include <concurrent_vector.h>

Concurrency::concurrent_vector<int> ++ 11.

.

0

, . ;

static int mutex=1;
int signal(int &x)
{
    x+=1;
    return 0;
}
int wait(int &x)
{
    x-=1;
    while(x<0);
    return 0;
}
for( int i = 0; i < input.rows; i++ )
{
    if(IsGoodMatch(input[I])
    {
        Newvalues newValues;
        newValues.x1=input.x1;
        newValues.x2=input.x1*2;
        wait(mutex);
        output.push_back( newValues);
        signal(mutex);
    }
} 

, .

-8

All Articles