difference between omp critical and omp single

前端 未结 2 520
清酒与你
清酒与你 2021-01-30 13:17

I am trying to understand the exact difference between #pragma omp critical and #pragma omp single in OpenMP:

Microsoft definitions for these a

2条回答
  •  轮回少年
    2021-01-30 13:34

    single and critical are two very different things. As you mentioned:

    • single specifies that a section of code should be executed by single thread (not necessarily the master thread)
    • critical specifies that code is executed by one thread at a time

    So the former will be executed only once while the later will be executed as many times as there are of threads.

    For example the following code

    int a=0, b=0;
    #pragma omp parallel num_threads(4)
    {
        #pragma omp single
        a++;
        #pragma omp critical
        b++;
    }
    printf("single: %d -- critical: %d\n", a, b);
    

    will print

    single: 1 -- critical: 4
    

    I hope you see the difference better now.

    For the sake of completeness, I can add that:

    • master is very similar to single with two differences:
      1. master will be executed by the master only while single can be executed by whichever thread reaching the region first; and
      2. single has an implicit barrier upon completion of the region, where all threads wait for synchronization, while master doesn't have any.
    • atomic is very similar to critical, but is restricted for a selection of simple operations.

    I added these precisions since these two pairs of instructions are often the ones people tend to mix-up...

提交回复
热议问题