gpt4 book ai didi

c++ - cout 最慢的处理器 MPI

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:48 25 4
gpt4 key购买 nike

我正在使用 MPI 编写程序。每个处理器执行一个for循环:

int main(int argc, char** argv) {
boost::mpi::environment env(argc, argv);

for( int i=0; i<10; ++i ) {
std::cout << "Index " << i << std::endl << std::flush;
}
}

有没有办法让 cout 只发生在最后一个处理器命中索引 i?还是标记一条线只在到达它的最后一个处理器上执行?

最佳答案

这可能看起来微不足道,但实际上,您在这里提出的问题对于 MPI 等分布式内存模型来说极其复杂......

在共享内存环境中,例如 OpenMP,这可以通过定义共享计数器轻松解决,由所有线程自动递增,然后检查它的值是否与线程数相对应。如果是这样,那就意味着所有线程都通过了该点,当前是最后一个,他将负责打印。

在分布式环境中,定义和更新这样的共享变量非常复杂,因为每个进程都可能在远程机器上运行。为了仍然允许这一点,MPI 从 MPI-2.0 开始提出内存窗口和单边通信。然而,即使这样,也不可能正确地实现原子计数器增量,同时可靠地获取它的值。只有在 MPI 3.0 和 MPI_Fetch_and_op() 函数的引入下,这才成为可能。下面是一个实现示例:

#include <mpi.h>
#include <iostream>

int main( int argc, char *argv[] ) {

// initialisation and inquiring of rank and size
MPI_Init( &argc, &argv);

int rank, size;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
MPI_Comm_size( MPI_COMM_WORLD, &size );

// creation of the "shared" counter on process of rank 0
int *addr = 0, winSz = 0;
if ( rank == 0 ) {
winSz = sizeof( int );
MPI_Alloc_mem( winSz, MPI_INFO_NULL, &addr );
*addr = 1; // initialised to 1 since MPI_Fetch_and_op returns value *before* increment
}
MPI_Win win;
MPI_Win_create( addr, winSz, sizeof( int ), MPI_INFO_NULL, MPI_COMM_WORLD, &win );

// atomic incrementation of the counter
int counter, one = 1;
MPI_Win_lock( MPI_LOCK_EXCLUSIVE, 0, 0, win );
MPI_Fetch_and_op( &one, &counter, MPI_INT, 0, 0, MPI_SUM, win );
MPI_Win_unlock( 0, win );

// checking the value of the counter and printing by last in time process
if ( counter == size ) {
std::cout << "Process #" << rank << " did the last update" << std::endl;
}

// cleaning up
MPI_Win_free( &win );
if ( rank == 0 ) {
MPI_Free_mem( addr );
}
MPI_Finalize();

return 0;
}

如您所见,对于这样一个微不足道的请求来说,这是相当冗长和复杂的。此外,这需要 MPI 3.0 支持。

不幸的是,对于您的目标而言,Boost.MPI 仅“支持 MPI 1.1 中的大部分功能”。因此,如果您真的想获得此功能,则必须使用一些简单的 MPI 编程。

关于c++ - cout 最慢的处理器 MPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32632818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com