0

我有 4 个线程,我想一次性启动 3 个函数。每个函数占用一个线程。
但是这段代码启动了每个函数 4 次

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

我有这个结果:

功能* 1 * 开始

功能* 1 * 开始

功能* 1 * 开始

功能* 1 * 开始

功能* 1 * 完成

功能* 1 * 完成

功能* 1 * 完成

功能* 1 * 完成

Func* 2 * 开始

Func* 2 * 开始

Func* 2 * 开始

Func* 2 * 开始

功能* 2 * 完成

功能* 2 * 完成

功能* 2 * 完成

功能* 2 * 完成

...

我应该如何更改代码以显示如下内容:

功能* 1 * 开始

Func* 2 * 开始

Func* 3 * 开始

功能* 2 * 完成

功能* 1 * 完成

功能* 3 * 完成

4

2 回答 2

5

您正在寻找的是sections工作共享结构。语法应如下所示:

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

我建议您参考其中的规范和示例,以获取有关此构造如何工作的更多信息。

于 2012-10-14T16:32:21.037 回答
1

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. E.g. 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, i.e. code that relies on thread IDs becomes somewhat non-portable. In contrast, the sections directive works with any number of threads, e.g. if there is only one thread, all sections would be executed sequentially.

于 2012-10-14T21:08:33.297 回答