简体   繁体   中英

OpenMP scheduler

I have problem with distributing tasks in the OpenMP. I have next code:

#include <stdio.h>
#include <unistd.h>

int cnttotal = 0;
int cnt1 = 0, cnt2 = 0;

int main()
{
    int i;
    #pragma omp parallel
    #pragma omp single nowait
    for (i = 0; i < 60; i++) {
        if (cnttotal < 1) {
            cnttotal++;
            #pragma omp task
            {
                #pragma omp atomic
                cnt1++;
                usleep(10);
                cnttotal--;
            }
        } else {
            #pragma omp task
            {
                #pragma omp atomic
                cnt2++;
                sleep(1);
            }
        }
    }

printf("cnt1 = %d; cnt2 = %d\n", cnt1, cnt2);

    return 0;
}

What would I didn't, cnt1 = 1 , cnt2 = 59 . I think that problem in OpenMP scheduler. Or is there something don't catch.

My feeling is that you confuse about task instantiation with the actual execution of a task. The #pragma omp task refers to the instantiaton of a task and that is extremely fast. Another thing is that an idle thread of the OpenMP runtime looks a list for ready tasks and executes it.

Going into the problem you posted. In this code is a running thread (say T1) enters the first iteration (i=0), thus it enters into the first if and then sets cnttotal to 1 and instantiates the first task (cnt1). After that instantiation, T1 keeps instantiating the remaining tasks while an idle thread (say T2) executes the task cnt1 which takes approx 10us and sets cnttotal to 0 again.

So in brief, what happens is the thread that instantiates any task is faster to execute than those 10us in task cnt1.

For instance, in my Intel(R) Core(TM) i7-2760QM CPU @ 2.40GHz if I changed the code so that the loop runs until i = 500 and sleeps 1 us (usleep (1)) I get:

cnt1 = 2; cnt2 = 498

which shows that instantiation of tasks is extremely fast.

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