Predefined private std :: vector in OpenMP, parallel to loop in C ++

I intend to use buffers std::vector<size_t> buffer(100), one in each thread in parallelizing the loop, as suggested in this code:

std::vector<size_t> buffer(100);
#pragma omp parallel for private(buffer)
for(size_t j = 0; j < 10000; ++j) {
    // ... code using the buffer ...
}

This code does not work. Although there is a buffer for each thread, the size can be 0.

How can I allocate a buffer at the beginning of each thread? Can i use #pragma omp parallel for? And I can do it more elegantly than this:

std::vector<size_t> buffer;
#pragma omp parallel for private(buffer)
for(size_t j = 0; j < 10000; ++j) {
    if(buffer.size() != 100) {
        #pragma omp critical
        buffer.resize(100);
    }
    // ... code using the buffer ...
}
+5
source share
2 answers

Divide the OpenMP scope as shown on this question .

Then declare the vector inside the outer region, but outside the for loop itself. This will make one local vector for each thread.

#pragma omp parallel
{
    std::vector<size_t> buffer(100);

#pragma omp for
    for(size_t j = 0; j < 10000; ++j) {
    {

        // ... code using the buffer ...

    }
}
+7
source

, , openMP .

++ private firstprivate -:

OpenMP v3.1:

private: undefined, . , .

firstprivate: .

. private , firstprivate .

std::vector , 0.

, , OpenMP:

std::vector<size_t> buffer(100, 0);  
#pragma omp parallel for firstprivate(buffer)
for (size_t j = 0; j < 10000; ++j) {
  // use the buffer
}

: ( OMP_STACKSIZE), . , .

+8

All Articles