这可能看起来微不足道,但实际上,对于分布式内存模型(例如 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 编程。