我能在OpenMP中为一个代码段分配多个线程吗?

6
我正在寻找一种使用多个线程并行执行代码段的方法。例如,如果我有16个线程和两个任务,我希望每个任务有8个线程同时执行。OpenMP有几个构造体(sectiontask)可以并行执行通用代码,但它们是单线程的。在我的情况下,使用sectiontask将导致一个线程执行这两个任务中的每一个,而其他14个线程则闲置。

在OpenMP中是否有类似的功能?如果有,如何实现?如果没有,我该使用什么工具?

感谢您的时间!

编辑2:

让我通过一个示例代码来扩展这个问题:

class some_class{
    void task(){
        cout<<"Entering the task method"<<endl;
        #pragma openmp parallel for
            for(int i=0; i < large_matrix.rows(); i++){
                 perform_thread_safe_operation(large_matrix.getRow(i));
            }
    }

    matrix large_matrix;
};


void main(){
    //I have 16 cores, so I want to spawn 16 threads
     some_class o1;
     some_class o2;
    // I want 8 of the 16 threads to execute this line:
    o1.task();
    // and 8 remaining threads to execute this line:
    o2.task();
}

我刚刚更新了我的答案并提供了解决方案。 - Mysticial
1个回答

10

您可以使用嵌套并行区域来实现此操作。

omp_set_nested(1);

#pragma omp parallel num_threads(2)
{
    if (omp_get_thread_num() == 0){
#pragma omp parallel num_threads(8)
        {

            //  Task 0

        }
    }else{
#pragma omp parallel num_threads(8)
        {

            //  Task 1

        }
    }
}

或者,你可以这样做:

#pragma omp parallel num_threads(16)
{
    if (omp_get_thread_num() < 8){
        //  Task 0
    }else{
        //  Task 1
    }
}
注意,如果OpenMP决定使用少于16个线程,此代码将不起作用。你需要插入自己的清理代码来解决这个问题。
编辑:针对您的更新:
class some_class{
    void task(){
        cout<<"Entering the task method"<<endl;

#pragma omp parallel for num_threads(8)
        for(int i=0; i < large_matrix.rows(); i++){
            perform_thread_safe_operation(large_matrix.getRow(i));
        }
    }

    matrix large_matrix;
};


void main(){

    omp_set_nested(1);

    //I have 16 cores, so I want to spawn 16 threads
     some_class o1;
     some_class o2;

#pragma omp parallel num_threads(2)
   {
       if (omp_get_thread_num() == 0){
           // I want 8 of the 16 threads to execute this line:
           o1.task();
       }else{
           // and 8 remaining threads to execute this line:
           o2.task();
       }
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接