c++ - openmp 程序卡在 block 的末尾

标签 c++ multithreading openmp

我正在编写一个程序,用于模拟读写器问题,不生成任何线程。一些线程被分配给读取器的任务,其中一些是写入器线程。维护标志数组以确保为每个循环分配不同的写入器线程迭代。 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/

相关文章:

c++ - 我可以使用字符串变量作为 fstream 的文件名吗? C++

c++ - 在 Visual C++ 中是否有可视化缓存的工具?

C++ 等效于从 popen 读取的 fgets

c++ - 从值数组创建直方图/绘图

c++ - Debian amd64 上的 GCC 4.7.2 - 内置原子增量?

c++ - 为什么此代码(在 Matlab 的 MEX 文件中使用 OpenMP)给出不同的结果?

java - `监控java中每个线程的cpu使用情况?

c# - Rx Task.Factory.StartNew 在 .Net 3.5 问题上启动两个任务

c++ - Cmake 不适用于 Maverick 上的 openMP

c - 使用 MPI 或 openMP 在 c 中进行循环并行化的最佳方法