2011-09-06 5 views
5

私は、セクションごとに複数のスレッドを使用して、コードのセクションを並列に実行する方法を探しています。たとえば、私は16のスレッドと2つのタスクを持っている場合、私は8つのスレッドがそれぞれ同時に2つのタスクを実行したい。 OpenMPは一般的なコードを並列に実行するいくつかの構造体(sectiontask)を持っていますが、それらはシングルスレッドです。私のシナリオでは、sectionまたはtaskを使用すると、1つのスレッドが2つのタスクのそれぞれを実行し、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個の未満のスレッドを使用することを決定した場合、このコードは動作しません。そのために独自のクリーンアップコードを挿入する必要があります。

EDIT:あなたの更新に応じて:

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(); 
     } 
    } 
} 
関連する問題