![](/img/trans.png)
[英]How to broadcast or send a single value to multiple processes (but not all of them)?
[英]How to pass two dimension array to all processes using broadcast?
我很难使MPI_Bcast
函数正常工作。 我想向所有进程广播二维数组。 似乎广播消息不起作用,因为从属进程正在读取的第一个消息是使它们存在其功能的一条消息-当使用DIETAG
时,功能退出。
谁能说出使用广播功能将二维数组传递到slace进程的正确方法是什么?
#include <stdio.h>
#include <iostream>
#include <string>
#include <time.h>
#include <mpi.h>
using namespace std;
/* Global constants */
#define MASTER 0
#define WORKTAG 1
#define DIETAG 2
#define MATRIX_SIZE 100
/* Local functions */
static void master(void);
static void slave(void);
static void initialize_matrix(int (*matrix)[MATRIX_SIZE]);
/* Function executed when program is started */
int main(int argc, char **argv)
{
// Declaring/Initizing local variables
int current_rank;
// Initialize MPI
MPI_Init(&argc, &argv);
// Finding out current procces identity in the default communicator
MPI_Comm_rank(MPI_COMM_WORLD, ¤t_rank);
if (current_rank == MASTER) {
master();
} else {
slave();
}
// Shut down MPI
MPI_Finalize();
return 0;
}
/* Function executed by "master" process */
static void master(void)
{
// Declaring variables
int matrix_one[MATRIX_SIZE][MATRIX_SIZE];
int processes_count, current_process_rank;
// Initializing variables
initialize_matrix(matrix_one);
MPI_Comm_size(MPI_COMM_WORLD, &processes_count);
MPI_Comm_rank(MPI_COMM_WORLD, ¤t_process_rank);
// this is currently not working
MPI_Bcast(&matrix_one, MATRIX_SIZE * MATRIX_SIZE, MPI_INT, current_process_rank, MPI_COMM_WORLD);
// Tell all the slaves to exit by sending an empty message with the DIETAG
for (current_process_rank = 1; current_process_rank < processes_count; current_process_rank++) {
MPI_Send(0, 0, MPI_INT, current_process_rank, DIETAG, MPI_COMM_WORLD);
}
}
/* Function executed by "slave" processes_count */
static void slave(void) {
MPI_Status status;
int current_process_rank;
int matrix_one[MATRIX_SIZE][MATRIX_SIZE];
MPI_Comm_rank(MPI_COMM_WORLD, ¤t_process_rank);
//received
while(1) {
MPI_Recv(&matrix_one, MATRIX_SIZE * MATRIX_SIZE, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
// Check the tag of the received message
if (status.MPI_TAG == DIETAG) {
return;
}
cout<<"value"<<matrix_one[0][0];
}
}
/* Function for populating matrix with random numbers */
static void initialize_matrix(int (*matrix)[MATRIX_SIZE])
{
int row, col;
for (row = 0; row < MATRIX_SIZE; row++)
{
for (col = 0; col < MATRIX_SIZE; col++)
{
matrix[row][col] = rand();
}
}
}
对于开始使用MPI的人来说,这是一个常见错误。 MPI通信器中的所有进程都应调用集体操作。 它们仅与相同类型的其他呼叫匹配。
不要将MPI_Bcast
视为一个向一堆其他进程发送一堆消息的单个进程。 相反,可以将其视为一堆协同工作的进程,以便在MPI_Bcast
结束时,所有进程都具有相同的数据。 这要求它们都调用MPI_Bcast
而不是一个进程广播,而所有其他都调用MPI_Send
。
这里有一个很好的教程,介绍如何使用简单的集合函数: http : //mpitutorial.com/mpi-broadcast-and-collective-communication/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.