Home > Backend Development > C++ > How to Perform Array Reduction in OpenMP?

How to Perform Array Reduction in OpenMP?

Susan Sarandon
Release: 2024-12-02 18:13:12
Original
596 people have browsed it

How to Perform Array Reduction in OpenMP?

Array reduction in OpenMP

Question:

How to perform it in OpenMP for arrays Reduction operation?

Answer:

OpenMP does support array reduction. There are two ways to do this:

Method 1: Use "private" variables

to create a private copy of S for each thread, populate them in parallel, and then Merge them into S in the area:

int A[] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13};
int S[10] = {0};
#pragma omp parallel
{
    int S_private[10] = {0};
    #pragma omp for
    for (int n = 0; n < 10; ++n)
    {
        for (int m = 0; m <= n; ++m)
        {
            S_private[n] += A[m];
        }
    }
    #pragma omp critical
    {
        for (int n = 0; n < 10; ++n)
        {
            S[n] += S_private[n];
        }
    }
}
Copy after login

method 2: Create an array of dimension 10*nthreads using multidimensional array

, fill it in parallel, and then merge it into S without critical section:

int A[] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13};
int S[10] = {0};
int *S_private;
#pragma omp parallel
{
    const int nthreads = omp_get_num_threads();
    const int ithread = omp_get_thread_num();

    #pragma omp single
    {
        S_private = new int[10 * nthreads];
        for (int i = 0; i < (10 * nthreads); i++)
            S_private[i] = 0;
    }
    #pragma omp for
    for (int n = 0; n < 10; ++n)
    {
        for (int m = 0; m <= n; ++m)
        {
            S_private[ithread * 10 + n] += A[m];
        }
    }
    #pragma omp for
    for (int i = 0; i < 10; i++)
    {
        for (int t = 0; t < nthreads; t++)
        {
            S[i] += S_private[10 * t + i];
        }
    }
}
delete[] S_private;
Copy after login

The above is the detailed content of How to Perform Array Reduction in OpenMP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template