我正在编写一个程序,用于模拟读写器问题,不生成任何线程。一些线程被分配给读取器的任务,其中一些是写入器线程。维护标志数组以确保为每个循环分配不同的写入器线程迭代。 RW 是我为读写操作编写的类。程序工作正常,直到循环的第一次迭代接近尾声。但在并行部分程序结束时挂起。
#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;
最佳答案
您的程序不是有效的 OpenMP 代码。 sections
是一个工作共享结构,因此团队中的所有线程都必须遇到,即使没有足够的部分来满足所有线程(OpenMP Specification,第 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.
将它放在 if
运算符的一个分支中意味着某些线程不会遇到它。实际上,这会导致在 sections
构造末尾的隐式屏障处挂起。我不确定您到底想达到什么目的,但必须以某种方式重组代码。
关于c++ - openmp 程序卡在 block 的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657956/