c++ - 避免在 C++ MPI 中为 cout 重复 if 语句

标签 c++ mpi cout ostream

我正在用 MPI(C 接口(interface),无提升等)编写一个 C++ 程序。在我的程序中,我有很多输出,无论是 cout 还是文件,都只在等级 0 上完成。是否有避免的好方法 写作 if (rank == 0) cout << string

有两种方法可以在我的计算机上使用我的 MPI 实现,但对我来说这两种方法都不稳定:

if (rank != 0)
  cout.setstate(ios_base::badbit);

这有效地禁用了除 0 以外的所有等级的输出,但它被允许吗?这样做会不会有问题?

另一个想法是创建一个未打开的 ofstream,并将输出重定向到那里。

ostream* os;
ofstream nullstream;
if (rank == 0)
  os = &cout;
else
  os = &nullstream;
*os << "rank " << rank << endl;

这使 nullstream 处于错误状态,但实际上也禁用了所有非 0 的等级上的输出...

这个问题对我来说似乎很常见,所以如果它已经在其他地方得到回答,我很抱歉。我没有通过搜索找到答案,很高兴能重定向到现有问题。

最佳答案

如果您愿意牺牲 Windows 系统的可移植性,在 POSIX 系统上静音输出的正确方法是将标准输出(以及可选的标准错误)重定向到 /dev/null:

int main() {
   ...
   std::ofstream sink("/dev/null");

   if (rank != 0) {
     // Mute standard output
     std::cout.rdbuf(sink.rdbuf());
     // Optionally mute standard error
     std::cerr.rdbuf(sink.rdbuf());      
   }

   no_output_from_other_ranks_from_now_on();
   ...
}

改编自this answer .

关于c++ - 避免在 C++ MPI 中为 cout 重复 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25545089/

相关文章:

c++ - 是否有理由将无符号类型用于非负常量?

c++ - 构造函数继承在 C++ 中是如何工作的?

python - MPI4Py 分散 sendbuf 参数类型?

c - MPI中3D过程分解中交换2D光晕的子数组数据类型的数量

c++ - C++ cout不能以正确的格式显示十六进制字节

java - 浮点错误

c++ - 来自简单程序的奇怪符号

c++ - curl_easy_perform() 是同步的还是异步的?

c++ - 从嵌套的 QStandardItemModel 中的特定列中提取所有数据

mpi - openmpi mpirun v1.8 中 --map-by 选项的语法