OpenMP Parallel Sections

suggest change

This example illustrates the basics of executing sections of code in parallel.

OpenMP pragmas need no header. A supported compiler still has to be told to enable OpenMP and link its runtime, for example with -fopenmp or /openmp. You may wish to include omp.h if you want to use any of the OpenMP API features.

Sample Code

std::cout << "begin ";
//    This pragma statement hints the compiler that the
//    contents within the { } are to be executed in as
//    parallel sections using openMP, the compiler will
//    generate this chunk of code for parallel execution
#pragma omp parallel sections
{
    //    This pragma statement hints the compiler that
    //    this is a section that can be executed in parallel
    //    with other section, a single section will be executed
    //    by a single thread.
    //    Note that it is "section" as opposed to "sections" above
    #pragma omp section
    {
        std::cout << "hello " << std::endl;
        /** Do something **/
    }
    #pragma omp section
    {
        std::cout << "world " << std::endl;
        /** Do something **/
    }
}
//    This line will not be executed until all the
//    sections defined above terminate
std::cout << "end" << std::endl;

Outputs

begin is printed first and end last. The two words can appear in either order. The insertions are unsynchronized, so this is a data race and the characters can also interleave.

OUTPUT A OUTPUT B
begin hello world end begin world hello end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents