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?
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.
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.