[英]ofstream variable cannot appear in OpenMP firstprivate?
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;
}
but the compiler show me the error: 但编译器显示错误:
error: use of deleted function 'std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const std::basic_ofstream<_CharT, _Traits>&) [with _CharT = char; 错误:使用已删除的函数'std :: basic_ofstream <_CharT,_Traits> :: basic_ofstream(const std :: basic_ofstream <_CharT,_Traits>&)[with _CharT = char; _Traits = std::char_traits]' _Traits = std :: char_traits]'
/usr/include/c++/5/fstream:723:7: note: declared here basic_ofstream(const basic_ofstream&) = delete; / usr / include / c ++ / 5 / fstream:723:7:注意:这里声明为basic_ofstream(const basic_ofstream&)= delete;
error: 'myfile' not specified in enclosing parallel 错误:'myfile'未在封闭并行中指定
firstprivate
works by making a thread-private copy of the value. firstprivate
通过制作值的线程私有副本来工作。 This does not work with streams, because you cannot copy them. 这不适用于流,因为您无法复制它们。 You cannot safely write to a file just by having multiple streams of it open. 您只能通过打开多个流来安全地写入文件。 There are basically two options: 基本上有两种选择:
Have a shared stream , protect all threaded access to it with #pragma omp critical
. 拥有共享流 ,使用#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; }
Open one stream for each thread on a different file . 为另一个文件上的每个线程打开一个流。
#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; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.