1

I'm new at OpenMP and I want to make multithread program. So I have txt file

London 2
A
B
Miami 3
C
D
E

And when I read my file I put all my data into struct called LetterStruct

struct LetterStruct{
    string city;
    int nr;
    string letters[ARRAY_SIZE];
};

I want to print my data something like like that(I know that order will be different each time I run my program)

thread_0 A
thread_0 B
thread_1 C
thread_1 D
thread_1 E

so each thread should print one of the city's letters(for example thread 0 should print London and thread 1 should print Miami letters)

so here what I did

void setUpThreads(int arraySize) {
    LetterStruct letter;
    omp_set_num_threads(2); // number of threads 2 (because 2 Miami and London)
    for (int j = 0; j < 1; j++) {
        #pragma omp parallel private(letter)
        {
            int id = omp_get_thread_num();
            letter = letterArray[j]; // get struct info
            for (int i = 0; i < ARRAY_SIZE; i++) {
                cout << "thread_" << id << " " << letter.letters[i] << endl;
            }
        }
    }
}

And here's my result

thread_0 thread_1 A
A
thread_0 thread_1 B
B
thread_0 thread_1 C
thread_1 C
thread_0 thread_1 D
thread_1 D
thread_0 thread_1 E
thread_1 E

it seems that both threads have Miami and London letter information (but I made this private(letter)) and for some reason everything prints incorrectly... So what I'm missing?

1 Answer 1

3

Currently, your threads are duplicating work. That is, they are both doing exactly the same thing. What the #pragma omp parallel does is tell the code to do everything in the enclosed brackets for each thread. This is not what you want it to do. Instead, replace your #pragma omp parallel private(letter) with a #pragma omp parallel for private(letter) right above the for loop. This will tell your code to split up each iteration of the loop to different threads.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but I tried that earlier and I get expected a for loop following openmp 'parallel for' directive
You got that when you put right before the for loop? That error message would not make any sense, since you have a for loop following the parallel for directive. Are you sure you didn't put the #pragma in the wrong place?
I put #pragma omp parallel for private(letter) before first for loop for (int j = 0; j < 1; j++) and I get this error
@David: Update your question with the code that you have using parallel for. Unless you're compiler is seriously broken, there is something else with that #pragma that you are doing wrong.
@David: For reference, here is code that works as you intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.