c++ - 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”
解决方案
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; } }
推荐阅读
- node.js - NodeJS 服务器在 AWS 中使用 Multer 上传大文件
- connection - 子模块如何通信
- android - 数据库被锁定(代码 5):,编译时:PRAGMA journal_mode MULTIPLE DATABASES
- android - 如何取消另一个应用程序的正在进行的通知?
- python-2.7 - 用于使用表单的 Python 脚本
- maven - 从基于 maven 的项目中提取所有 jar 依赖项并将它们添加到 tomcat lib
- mongodb - mongodb 4.0 对 node.js 的事务支持
- mysql - 未登录的用户可以看到由carrierwave保存的文件
- android - Android P Beta - AlarmManager 通知不起作用
- java - 我们可以找到存储在数据库中的两个位置之间的实时最短距离吗