본문 바로가기

C++/ 병렬처리에서 std::vector의 push_back() 사용하기

2020. 3. 3.

std::vector의 push_back() 함수를 사용하면 충돌현상이 발생함

 

1. 따라서 push_back()이 발생할 때 아래처럼 처리하면 push_back()의 효과를 낼 수 있음

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);

 

2. 또는 멀티 쓰레드 처리를 위해 개발된 concurrency vector의 push_back()을 사용하면 됨

#include <concurrent_vector.h>
Concurrency::concurrent_vector<int> // in c++11.

 

https://stackoverflow.com/questions/19268217/stdvector-push-back-fails-when-used-in-a-parallel-for-loop

 

std::vector push_back fails when used in a parallel for loop

I have a code that is as follow (simplified code): for( int i = 0; i < input.rows; i++ ) { if(IsGoodMatch(input[I]) { Newvalues newValues; newValues.x1=input.x1;

stackoverflow.com

 

댓글