流变量不能出现在 OpenMP 第一私有中?

ofstream variable cannot appear in OpenMP firstprivate?

本文关键字:OpenMP 不能 变量      更新时间:2023-10-16

code

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>&( [_CharT = char; _Traits = std::char_traits]'

/usr/include/c++/5/fstream:723:7:注意:此处声明 basic_ofstream(常量 basic_ofstream&( = 删除;

错误:在封闭并行中未指定"myfile">

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;
    }
    }