简体   繁体   中英

How to get OpenMP to work with #pragma omp task?

I'm using OpenMP with Linux terminal. I compile my program with the flag -fopenmp . The environment I'm using does support multithreading.

    #pragma omp parallel num_threads(3)
    {
        #pragma omp task
            R11Inverted = compute_inverse(r11, half);
        #pragma omp task
            printf("5 I am thread # %d\n", omp_get_thread_num());
            R22Inverted = compute_inverse(r22, half);
    }

As a simple and minimum test, all I want to do is get printf("5 I am thread # %d\n", omp_get_thread_num()); to show that the program is running with three threads. Basically omp_get_thread_num() should return values either 0, 1, or 2.

The Output The block of code above is called many times repeatedly. However the results every time is showing that threading is not working and the program is only using a single thread (Thread 0).

You are missing the {} around the block of code and also the single clause.

Try the following:

#pragma omp parallel num_threads(3)
{
        #pragma omp single
        {
            #pragma omp task
               R11Inverted = compute_inverse(r11, half);
            #pragma omp task
            {
              printf("5 I am thread # %d\n", omp_get_thread_num());
              R22Inverted = compute_inverse(r22, half);
            }
        }
}

However the results every time is showing that threading is not working and the program is only using a single thread (Thread 0).

If you want to check if it being called by multithreads use instead omp_get_num_threads , which returns the number of threads which the team.

   #pragma omp parallel num_threads(3)
   {
            #pragma omp master
            {           
                printf("Total Threads # %d\n", omp_get_num_threads()); 
            }
            #pragma omp single
            {
                #pragma omp task
                   R11Inverted = compute_inverse(r11, half);
                #pragma omp task
                {
                  printf("5 I am thread # %d\n", omp_get_thread_num());
                  R22Inverted = compute_inverse(r22, half);
                }
            }
    }

If the code above is call recursively then you need to adapt to the following:

   #pragma omp parallel num_threads(3)
   {
      #pragma omp master      
      printf("Total Threads # %d\n", omp_get_num_threads()); 
      #pragma omp single
      compute_inverse(...); // First call to the recursive function
   }

and inside the compute_inverse function:

   #pragma omp task
   R11Inverted = compute_inverse(r11, half);
   #pragma omp task
   {
      printf("5 I am thread # %d\n", omp_get_thread_num());
      R22Inverted = compute_inverse(r22, half);
   }

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