Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

How does the SECTIONS directive in OpenMP distribute work?

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, 
", omp_get_thread_num());
    }

    #pragma omp section
    { 
        printf ("id = %d, 
", 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, 
", omp_get_thread_num());
    }

    #pragma omp section
    { 
        printf ("id = %d, 
", omp_get_thread_num());
    }
}

#pragma omp sections
{
    #pragma omp section
    { 
        printf ("id = %d, 
", omp_get_thread_num());
    }

    #pragma omp section
    { 
        printf ("id = %d, 
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, 
", omp_get_thread_num());
    }

    #pragma omp section
    { 
        printf ("id = %d, 
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...