User Tools

Site Tools


c:mpi:broadcast

MPI Broadcast

MPI program using MPI_Bcast for broadcasting a message from one process (typically the master process) to all other processes in the communicator.
This example will demonstrate how a single value can be sent from one process to all others in a simple and efficient way using MPI's broadcast functionality.

mpi-broadcast.c
#include <mpi.h>
#include <stdio.h>
 
int main(int argc, char** argv) {
    // Initialize the MPI environment
    MPI_Init(&argc, &argv);
 
    // Get the rank of the process
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
 
    // Get the total number of processes
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
 
    // The broadcast value
    int broadcast_value;
 
    if (world_rank == 0) {
        // If we are the master process (rank 0), set the broadcast value
        broadcast_value = 100;
        printf("Process 0 broadcasting value %d\n", broadcast_value);
    }
 
    // Use MPI_Bcast to broadcast the value from process 0 to all processes
    MPI_Bcast(&broadcast_value, 1, MPI_INT, 0, MPI_COMM_WORLD);
 
    // All processes print the received value
    printf("Process %d received value %d\n", world_rank, broadcast_value);
 
    // Finalize the MPI environment.
    MPI_Finalize();
}

MPI Initialization: The MPI environment is initialized with MPI_Init.

Process Rank and Size: Each process finds out its rank and the total number of processes.

Broadcast Operation: The master process (rank 0) sets a value to be broadcasted. In this case, broadcast_value is set to 100. MPI_Bcast is used to broadcast the value. The parameters include the buffer containing the value to be broadcasted (broadcast_value), the number of elements in the buffer, the datatype of the buffer, the rank of the broadcasting process (0 in this case), and the communicator (MPI_COMM_WORLD).
All processes, including the master process, execute the MPI_Bcast call. The broadcasted value is then stored in broadcast_value on each process.

Output: Each process prints the received value to demonstrate that the broadcast was successful.

Finalization: The MPI environment is finalized with MPI_Finalize.

This program shows how MPI_Bcast can be used to efficiently distribute data from one process to all others.

c/mpi/broadcast.txt · Last modified: 2024/01/17 10:31 by odefta