【发布时间】:2019-04-09 04:43:17
【问题描述】:
我正在尝试解决家庭作业问题以调试以下单元测试。
基本上主进程生成随机整数并发送给子进程检查素数,结果传回主进程,算法结束。
我知道应该用集体交流来代替循环,但这是问题的另一部分。我想了解为什么我在这里的这段代码会导致死锁。
通过阅读其他questions,我知道发送/接收的数量应该相互匹配。但是,我看不出在我的代码中情况并非如此。
当前的行为是找到一个素数,将其发送回主进程,此时程序会挂起 - 直到使用 ctrl-C 手动取消。
我知道这不是解决这个问题的惯用方法,但我真的很想知道这个方法中的错误到底在哪里。
谢谢!
TEST_CASE("3a - Finding prime numbers", "[MPI]" )
{
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Random number generation
std::minstd_rand generator;
unsigned min(2342), max(12342340);
std::uniform_int_distribution<> distribution(min, max);
// candidates too big, one of the size values is the master node
std::vector<unsigned> candidates(size - 1);
// Main loop continues until a prime is found
int found_prime(0);
while (found_prime == 0) {
if (rank == 0) {
// Create some candidate numbers for each process to test
std::generate(candidates.begin(), candidates.end(),
[&]() { return distribution(generator); });
// Send one to each worker
for (int worker(1); worker < size; ++worker) {
int rc = MPI_Ssend(&candidates[worker - 1], 1, MPI_UNSIGNED,
worker, 0, MPI_COMM_WORLD);
REQUIRE(rc == MPI_SUCCESS);
}
// Receive whether it was prime
for (int worker(1); worker < size; ++worker) {
unsigned result;
int rc = MPI_Recv(&result, 1, MPI_UNSIGNED, worker, 0,
MPI_COMM_WORLD, MPI_STATUS_IGNORE);
REQUIRE(rc == MPI_SUCCESS);
if (result == 1) {
found_prime = candidates[worker - 1];
std::cout << "Worker " << worker << " found prime "
<< found_prime << std::endl;
}
}
} else {
// Receive the candidate to check
unsigned candidate;
int rc = MPI_Recv(&candidate, 1, MPI_UNSIGNED, 0, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
REQUIRE(rc == MPI_SUCCESS);
// Do the check
unsigned is_prime = mp::IsPrime(candidate) ? 1 : 0;
// Return the result
rc = MPI_Ssend(&is_prime, 1, MPI_UNSIGNED, 0, 0, MPI_COMM_WORLD);
REQUIRE(rc == MPI_SUCCESS);
}
}
std::cout << "Finished" << rank << std::endl;
}
【问题讨论】:
标签: c++ parallel-processing mpi