首页 > 解决方案 > ofstream 变量不能出现在 OpenMP firstprivate 中?

问题描述

代码

ofstream myfile("file_path");
#pragma omp parallel for default(none) schedule(dynamic) firstprivate(myfile) private(i)
for(i=0; i<10000; i++) {
    myfile<<omp_get_thread_num()+100<<endl;
}

但编译器向我显示错误:

错误:使用已删除的函数 'std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const std::basic_ofstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]'</p>

/usr/include/c++/5/fstream:723:7: 注意:在这里声明 basic_ofstream(const basic_ofstream&) = delete;

错误:未在封闭并行中指定“myfile”

标签: c++openmpofstream

解决方案


firstprivate通过制作值的线程私有副本来工作。这不适用于流,因为您无法复制它们。您不能仅通过打开多个流来安全地写入文件。基本上有两种选择:

  • 拥有一个共享流,保护所有线程访问它#pragma omp critical

    ofstream myfile("file_path");
    #pragma omp parallel for
    for (int i=0; i < 10000; i++) {
        #pragma omp critical
        myfile << (omp_get_thread_num()+100) << endl;
    }
    
  • 为不同文件上的每个线程打开一个流。

    #pragma omp parallel
    {
        ofstream myfile(std::string("file_path.") + std::to_string(omp_get_thread_num()));
        #pragma omp for
        for (int i=0; i < 10000; i++) {
            myfile << (omp_get_thread_num()+100) << endl;
        }
    }
    

推荐阅读