c++ - 我可以将多个线程分配给 OpenMP 中的一个代码段吗?

标签 c++ multithreading openmp

我正在寻找一种方法,对每个部分使用多个线程来并行执行代码部分。例如,如果我有 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();
}

最佳答案

您可以使用嵌套的平行区域来做到这一点。

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

关于c++ - 我可以将多个线程分配给 OpenMP 中的一个代码段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7322960/

相关文章:

c++ - 使用指针传递引用和值

c++ - std::conditional_variable::notify_all 不唤醒所有线程

fortran - 使用 OpenMP 关键和有序

c - 如何更改此 C 代码以预取一些数据?

c++ - 按平台划分的 CMake 输出目录

c++ - 错误: conflicting declaration of structure in multiple files

c++ - 识别内存泄漏

python - PyQt:如何在不卡住 GUI 的情况下更新进度?

java - java如何区分Lambda中的Callable和Runnable?

c++ - pi 计算的 OpenMP 并行化速度慢或错误