简体   繁体   中英

C++ openMP array is sequential

I have 2 arrays, one is int array and the other one is double array, I need to create struct array in which i save thread id, int, double values from array. I have n elements and n threads. I wrote following code, but somehow it prints results in sequential order, results are not mixed, so I am not really sure if it works in parallel at all. Code:

#include <iostream>
#include <omp.h>

using namespace std;

struct Data {
    int threadNumber;
    double doubleNumber;
    int intNumber;
};

int main() {

    int numbOfThreads = 20;
    omp_set_num_threads(numbOfThreads);
    double s2[50];
    double s1[50];
    Data allArray[50];

    for (int i = 0; i < numbOfThreads; i++) {
        s2[i] = i * 0.15;
        s1[i] = i;
    }

    int threadNumber = 0;

#pragma omp parallel private(threadNumber)
    {
        threadNumber = omp_get_thread_num();
        for (int i = threadNumber; i < 20; i++) {
            allArray[i].threadNumber = threadNumber;
            allArray[i].intNumber = s1[i];
            allArray[i].doubleNumber = s2[i];
        }
    }

    for (int i = 0; i < numbOfThreads; i++) {
        cout << allArray[i].threadNumber << " " << allArray[i].intNumber << " " << allArray[i].doubleNumber << endl;
    }

    return 0;

}

And console result:

0 0 0
1 1 0.15
2 2 0.3
1 3 0.45
1 4 0.6
1 5 0.75
6 6 0.9
7 7 1.05
8 8 1.2
9 9 1.35
10 10 1.5
11 11 1.65
12 12 1.8
13 13 1.95
14 14 2.1
15 15 2.25
16 16 2.4
17 17 2.55
18 18 2.7
19 19 2.85

Thread id values changes, but data is always in ascending order.

It appears that the loop is outside the parallelized portion of code. The loop steps sequentially through the data. This is what one would expect in this case. You can see artifacts of the multithreading in the threadNumber column, but this code:

        allArray[i].intNumber = s1[i];
        allArray[i].doubleNumber = s2[i];

ensures that the values will be the same no matter which thread is writing to the array since those values are just using the index from within the loop (within the thread).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM