代码
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/