OpenMP parity checking of the thread how?

Hi. Studying OpenMp, and performing the simplest tasks had questions.
I run 8 threads and I would want that even if the flow is to write the number 1 to the array number of the flow. Wrote such a program, but I don't understand why std::cout << thread%2 << std::endl; prints out the correct values, and the next line if (thread%2 ==0) not work out? This can be seen when in a critical block deduce the entire array. How to fix? Thank you.
int main()
{
 int i;
 int threads = 8;
 int thread;
 int table[8] = { 0,0,0,0,0,0,0,0 };
omp_set_num_threads(8);
#pragma omp parallel 
{
 thread = omp_get_thread_num();
 threads = omp_get_num_threads();

 for (i = thread;i < threads;i += threads) {
 std::cout << thread%2 << std::endl;
 if (thread%2 ==0) {
 table[thread] = 1;
}
}
#pragma omp critical 
{
 for (i = thread;i < threads;i += threads)
{
 std::cout << table[i] << std::endl;
}
}

}
}
July 2nd 19 at 13:09
1 answer
July 2nd 19 at 13:11
Solution
1) your for (i = thread;i < threads;i += threads) does nothing and is equivalent to int i = thread;
2) when you print the array as a whole, the threads can print the values in a random order. print room thread, which prints the value

3) not immediately noticed. variables that you declare outside pragma omp shared for all threads. in the end, the variable stream number is overwritten by another thread. and at the time of comparison in a variable will have the value of another thread.

int main()
{
 int thread;
 int table[8] = { 0 };
omp_set_num_threads(8);
#pragma omp parallel private(thread)//everything else in the brackets will run 8 threads simultaneously
 { //threads to control in a random order
 thread = omp_get_thread_num(); //each thread gets its own room
 if (thread%2 ==0) //even flows recorded in the plate unit
 table[thread] = 1;
#pragma omp critical //critical section at a time can execute only one thread
 { //this is necessary to print from different threads are not mixed
 std::cout << "Hello, I am thread no" << thread << std::endl;
 std::cout << "My table value is" << table[thread] << std::endl;
 } //threads are in the section also in random order
}
}
Thank you. But the problem is, I already so tried, then the console goes like this: joxi.ru/BA09pNncJlkgbr
I too do not understand why the thread number in the console is the same, several times. Well, every time it's different. I already double check poked, but something isn't right. - Macie commented on July 2nd 19 at 13:14
ahh, the thread variable outside pragma omp described! common at all. and the threads she was assigned in turn. in the end it became equal three.

specify
#pragma omp parallel private(thread) - turner.Beahan commented on July 2nd 19 at 13:17
: You saved my nerves, if there is still something left... Thanks for the help! - Macie commented on July 2nd 19 at 13:20

Find more questions by tags C++