The pre allocated private STD:: vector in OpenMP is parallelized into a loop in C

I'm going to use the buffer STD:: vector < size_ t> Buffer (100), one in each thread of loop parallelization, as shown in the 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 each thread has a buffer, their size is 0. 5

How do I allocate buffers at the beginning of each thread? Can I still use #pragma OMP parallel? I can do this more gracefully 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 ...
}

Solution

Split the OpenMP area, as shown in this question

The vector is then declared in the outer region, but outside the for loop itself This creates a 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 ...

    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>