In OpenMP when using omp sections
, will the threads be distributed to the blocks inside the sections, or will each thread be assigned to each sections?
When nthreads == 3
:
#pragma omp sections { #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } }
Output:
id=1 id=1
But when I execute the following code:
#pragma omp sections { #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } } #pragma omp sections { #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } }
Output:
id=1 id=1 id=2 id=2
From these output I can't understand what the concept of sections is in OpenMP.
SummaryThe sections construct is a non-iterative worksharing construct that contains a set of structured blocks that are to be distributed among and executed by the threads in a team. Each structured block is executed once by one of the threads in the team in the context of its implicit task.
Following segments must be preceded by an omp section directive. All omp section directives must appear within the lexical construct of the program source code segment associated with the omp sections directive.
OpenMP directives exploit shared memory parallelism by defining various types of parallel regions. Parallel regions can include both iterative and non-iterative segments of program code.
2.1 Directive Format. Each directive starts with #pragma omp. The remainder of the directive follows the conventions of the C and C++ standards for compiler directives. In particular, white space can be used before and after the #, and sometimes white space must be used to separate the words in a directive.
The code posted by the OP will never execute in parallel, because the parallel
keyword does not appear. The fact that the OP got ids different from 0 shows that probably his code was embedded in a parallel directive. However, this is not clear from his post, and might confuse beginners.
The minimum sensible example is (for the first example posted by the OP):
#pragma omp parallel sections { #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } #pragma omp section { printf ("id = %d, \n", omp_get_thread_num()); } }
On my machine, this prints
id = 0, id = 1,
showing that the two sections are being executed by different threads.
It's worth noting that however this code can not extract more parallelism than two threads: if it is executed with more threads, the other threads don't have any work to do and will just sit down idle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With