c++ - ofstream 变量不能出现在 OpenMP firstprivate 中?

标签 c++ openmp ofstream

代码

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

但是编译器告诉我错误:

error: use of deleted function ‘std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const std::basic_ofstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]’

/usr/include/c++/5/fstream:723:7: note: declared here basic_ofstream(const basic_ofstream&) = delete;

error: ‘myfile’ not specified in enclosing parallel

最佳答案

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

  • 有一个共享流,使用#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;
        }
    }
    

关于c++ - ofstream 变量不能出现在 OpenMP firstprivate 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51007067/

相关文章:

c++ - 使用 UTF-8 和 PuTTY 时,NCURSES 边框打印为 q、x

c++ - 在 ROI 中使用 findContours,轮廓坐标错误

C++错误不那么冗长

c++ - OpenMP 卸载到 Nvidia 错误减少

cmake - clang、openMP 和 CMake

c++ - 为什么将 'ifstream' 和 'ofstream' 添加到 "std"中,而 'fstream' 可以同时满足这两个目的?

c++ - 何时使用 Boost.Locale 进行大小写折叠以及何时整理?

c - 如何使用不同的线程使用openmp安全地更新C结构

C++ 不正确的循环算法(或文件处理问题)

c++ - 在具有动态路径C++的文件夹中写入文件