简体   繁体   中英

(OpenMP) How to start each function 1 time in 1 thread

I have 4 threads and I want to start in one time 3 functions. Each function takes one thread.
But this code is starting every function 4 times

#pragma omp parallel
    {
        Func1();
        Func2();
        Func3();
    }

and I have this result:

Func* 1 * started

Func* 1 * started

Func* 1 * started

Func* 1 * started

Func* 1 * finished

Func* 1 * finished

Func* 1 * finished

Func* 1 * finished

Func* 2 * started

Func* 2 * started

Func* 2 * started

Func* 2 * started

Func* 2 * finished

Func* 2 * finished

Func* 2 * finished

Func* 2 * finished

...

How should I change the code to display some like this:

Func* 1 * started

Func* 2 * started

Func* 3 * started

Func* 2 * finished

Func* 1 * finished

Func* 3 * finished

What you are searching for is the sections worksharing construct. The syntax should be the following:

#pragma omp parallel
{
#pragma omp sections
  {
#pragma omp section
    Func1();
#pragma omp section
    Func2();
#pragma omp section
    Func3();
  }
}

I suggest you to refer to the specifications and the examples therein for more information on how this construct works.

As already answered by Massimiliano, the easiest way to achieve what you want is to use the sections construct:

#pragma omp parallel sections
{
    #pragma omp section
    Func1();
    #pragma omp section
    Func2();
    #pragma omp section
    Func3();
}

(when the sections construct is the only thing nested inside a parallel region, both pragmas can be combined as shown)

Each section scopes the statement or block immediately following it. Eg if you'd like to include some more code in a section, you should put it inside a block:

#pragma omp section
{
    Func1();
    SomeOtherFunc1();
}

A more general way to control what each thread does is to examine the thread ID as returned by omp_get_thread_num() and to branch in accordance. This resembles the way MPI programs are written:

#pragma omp parallel
{
    switch (omp_get_thread_num())
    {
        case 0:
            Func1();
            break;
        case 1:
            Func2();
            break;
        case 2:
            Func3();
            break;
        default:
            // Do nothing
     }
}

One obvious disadvantage is that it would only work unless there are at least 3 threads in the team that executes the parallel region, ie code that relies on thread IDs becomes somewhat non-portable. In contrast, the sections directive works with any number of threads, eg if there is only one thread, all sections would be executed sequentially.

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