【发布时间】:2020-08-08 12:42:42
【问题描述】:
在boost::mpi 中,一些集合操作,例如reduce,需要将操作传递给例程。我不确定这个操作的类型到底应该是什么。
以下最小示例编译时没有警告。
#include <iostream>
#include <boost/mpi/collectives.hpp>
int mysum(int a, int b) { return a + b; }
int main()
{
boost::mpi::environment env;
boost::mpi::communicator world;
int data = world.rank() + 1;
int data_reduced;
boost::mpi::reduce(world, data, data_reduced, mysum, 0);
if (world.rank() == 0)
std::cout << data_reduced << std::endl;
return 0;
}
但是,运行超过 1 个任务时会崩溃
$ mpirun -n 2 ./mpi
munmap_chunk(): invalid pointer
...
如下修改代码可使程序运行而不会崩溃。
#include <iostream>
#include <boost/mpi/collectives.hpp>
struct mysum {
int operator()(int a, int b) { return a + b; }
};
int main()
{
boost::mpi::environment env;
boost::mpi::communicator world;
int data = world.rank() + 1;
int data_reduced;
boost::mpi::reduce(world, data, data_reduced, mysum{}, 0);
if (world.rank() == 0)
std::cout << data_reduced << std::endl;
return 0;
}
(我知道这相当于std::plus,程序只是一个例子)
$ mpirun -n 2 ./mpi
3
有什么区别,为什么第二个版本有效?
编辑
问题也出现了,因为mysum 的两个变体都可以称为mysum(....),即两者都是callable。所以在这两种情况下,下面的代码都有效。
template <class Callable, class ArgType>
auto dosomething(ArgType a, ArgType b, Callable&& L) { return L(a, b); }
auto x = dosomething(mysum, 1, 2);
(这基本上等同于std::invoke)
【问题讨论】: