我可以为OpenMP中的代码段分配多个线程吗? [英] Can I assign multiple threads to a code section in OpenMP?

查看:385
本文介绍了我可以为OpenMP中的代码段分配多个线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来并行使用多个线程为每个部分执行代码段。例如,如果我有16个线程和两个任务,我想要8个线程每个同时执行这两个任务。 OpenMP有几个并行执行通用代码的构造( task ),但它们是单线程的。在我的场景中,使用任务将导致一个线程执行两个任务中的每一个, idly。

I'm looking for a way to execute sections of code in parallel using multiple threads for each section. For example, if I have 16 threads and two tasks, I want 8 threads each to simultaneously execute those two tasks. OpenMP has several constructs (section, task) that execute general code in parallel, but they are single-threaded. In my scenario, using section or task would result in one thread executing each of the two tasks, while 14 threads sit idly by.

OpenMP是否可能?

Is something like that even possible with OpenMP? If so, how do I do it, and if not, what can I use for that purpose?

感谢您的时间!

编辑2:

让我们使用示例代码扩展此问题:

Let me expand on this question with an example code:

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
    }
}

编辑:为了响应您的更新:

In response to your update:

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

这篇关于我可以为OpenMP中的代码段分配多个线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆