Reputation: 15
I am writing a program for generating no of threads for imitating reader-writer problem.Some of threads are assigned task of reader and some of them are writer threads.Flag array is maintained to assure different writer threads are assigned for each loop iteration. RW is class i have written for reading and writing operations.Program works fine till near end of 1st iteration of loop.But at the end of parallel section program hangs.
#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;
}
Upvotes: 0
Views: 576
Reputation: 74365
Your program is not a valid OpenMP code. sections
is a worksharing construct and as such must be encountered by all threads in the team, even when there are not enough sections to feed all the threads (OpenMP Specification, section 2.7):
Each worksharing region must be encountered by all threads in a team or by none at all, unless cancellation has been requested for the innermost enclosing parallel region.
Having it in just one branch of the if
operator means some threads will not encounter it. In practice this results in a hang at the implicit barrier at the end of the sections
construct. I'm not sure what exactly you are trying to achieve, but the code must be restructured somehow.
Upvotes: 1