2011-09-06 49 views
5

我正在寻找一种方法来并行执行代码段使用多个线程为每个部分。例如,如果我有16个线程和两个任务,我需要8个线程来同时执行这两个任务。 OpenMP有几个并行执行通用代码的构造(section,task),但它们是单线程的。在我的场景中,使用sectiontask将导致一个线程执行两个任务中的每一个,而14个线程则无效。我可以将多个线程分配给OpenMP中的代码部分吗?

就像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(); 
} 
+0

我刚刚更新了我的一个解决方案的答复。 – Mysticial

回答

8

为此,您可以使用嵌套并行区域。

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(); 
     } 
    } 
} 
相关问题