2017-01-15 20 views
0

私は、リーダライタの問題を模倣するためのスレッドを生成しないためのプログラムを書いています。スレッドの一部には読者のタスクが割り当てられており、その一部はライタスレッドです。ループの繰り返しごとに異なるライタースレッドが割り当てられるようにします。 RWは私が読み書き操作のために書いたクラスです。プログラムは、ループの最初の反復の終わり近くまでうまく動作します。しかし、並列セクションの最後にプログラムがハングします。ブロックの最後にopenmpプログラムが掛かっています

#include<iostream> 
#include<fstream> 
#include<omp.h> 

using namespace std; 

class RW 
{ 

string text,dsp,path; 
fstream f,r; 

public: RW(string p) 
{ 
    path=p; 
} 

public: void reader() 
{ 
    //cout<<"in reader\n"; 

    { 
     r.open(path.c_str(),ios::in); 
     r>>dsp; 
     cout<<dsp<<endl; 
     r.close(); 
    } 

} 

public: void writer() 
{ 
    f.open(path.c_str(),ios::out); 
    cout<<"Enter text to be written: "; 
    cin>>text; 
    cout<<endl; 
    f<<text; 
    //cout<<"end -- write \n"; 
    f.close(); 
} 


}; 
int main() 
{ 
    omp_lock_t lk; 
    omp_init_lock(&lk); 
    int flag[10]; 
    RW rw("a.txt"); 
    string dsp; 
    int th_no,no_th; 
    int wn,rn; 
    cout<<"Enter no of writer threads: "; 
    cin>>wn; 
    cout<<"\nEnter no of reader threads: "; 
    cin>>rn; 



for(int i=0;i<10;i++){flag[i]=0;} 
//omp_set_nested(1); 

for(int i=0;i<wn;i++) 
{ 
    cout<<i<<": loop"<<endl; 
    #pragma omp parallel default(shared) private(th_no) num_threads(wn+rn) 
    { 
     th_no = omp_get_thread_num(); 
     cout<<omp_get_thread_num()<<endl; 

     #pragma omp barrier 
     if(th_no<wn && flag[th_no]==0) 
     { 
     #pragma omp sections 
     { 

      #pragma omp section 
      { 
       cout<<"thread no: "<<omp_get_thread_num()<<endl; 
       omp_set_lock(&lk); 
       rw.writer(); 
       flag[omp_get_thread_num()]=1; 
       omp_unset_lock(&lk); 
      } 
     } 
     } 

     #pragma omp barrier 
     if(omp_get_thread_num()>=wn) 
     { 
      omp_set_lock(&lk); 
      cout<<"thread no:"<<omp_get_thread_num()<<endl; 
      rw.reader(); 
      omp_unset_lock(&lk); 
     } 
     #pragma omp barrier 
     #pragma omp flush 
     th_no=0; 
    } 


} 

return 0; 

}

+1

すべての前に 'public:'を置かないでください。これは一般的な方法でも、C#またはJavaでもありません。 – DeiDei

+0

私はちょうどコーディングを始めたばかりの初心者ですが、私はこれを念頭に置いて、thanx –

答えて

1

あなたのプログラムは、有効なOpenMPのコードではありません。 sectionsは、ワークシェアリング構造であり、そのようなものとして、すべてのスレッド(OpenMP Specification、セクション2.7)を供給するのに十分なセクションが存在しない場合であっても、チーム内のすべてのスレッドが遭遇しなければならない:

各ワークシェアリング領域が遭遇しなければなりませんチーム内のすべてのスレッドを含むことができます。また、最内周の並列領域に対して取り消しが要求されている場合を除き、すべてではありません。

ifオペレータの1つのブランチだけであれば、スレッドによってはそれが発生しないことを意味します。実際には、sections構成の最後の暗黙的な障壁でハングします。私はあなたが達成しようとしていることを正確には分かりませんが、コードはどうにか再構成されなければなりません。

+0

ありがとう...!それは働いた –

関連する問題