How to make threads write their numbers in reverse order using OpenMP?

I don’t really understand the purpose of what you are asking but this works

 #include "omp.h"
 #include <iostream>
 using namespace std;
 int main()
 {

#pragma omp parallel
{
      int nthreads = omp_get_num_threads();
      for(int i=nthreads-1; i>=0; i--)
      {
            #pragma omp barrier
            {
                  if(i==omp_get_thread_num())
                  {
                        #pragma omp critical
                        cout << "I am thread "<< i <<endl;
                  }
            }
      }
}
}

8 threads it outputs

I am thread 7
I am thread 6
I am thread 5
I am thread 4
I am thread 3
I am thread 2
I am thread 1
I am thread 0

Leave a Comment