Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <mpi.h>
- #include <unistd.h>
- const int tag = 42; /* Message tag */
- int id, ntasks, source_id, err, i;
- MPI_Status status;
- char msg[80]; /* Message array */
- int main(int argc, char *argv[]) {
- err = MPI_Init(&argc, &argv); /* Initialize MPI */
- if (err != MPI_SUCCESS) {
- printf("MPI_init failed!\n");
- exit(1);
- }
- err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
- if (err != MPI_SUCCESS) {
- printf("MPI_Comm_size failed!\n");
- exit(1);
- }
- err = MPI_Comm_rank(MPI_COMM_WORLD, &id); /* Get id of this process */
- if (err != MPI_SUCCESS) {
- printf("MPI_Comm_rank failed!\n");
- exit(1);
- }
- MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
- /* Check that we run on at least two processors */
- if (ntasks < 2) {
- printf("You have to use at least 2 processors to run this program\n");
- MPI_Finalize(); /* Quit if there is only one processor */
- exit(0);
- }
- /* Process 0 (the receiver) does this */
- if (id == 0) {
- for (i=1; i<ntasks; i++) {
- mpi_recv_msg();
- }
- }
- /* Processes 1 to N-1 (the senders) do this */
- else {
- mpi_send_msg(id);
- }
- err = MPI_Finalize(); /* Terminate MPI */
- if (err != MPI_SUCCESS) {
- printf("Error in MPI_Finalize!\n");
- exit(1);
- }
- if (id==0) printf("Ready\n");
- exit(0);
- }
- void mpi_send_msg(int id){
- sleep(id);
- int length;
- MPI_Get_processor_name(msg, &length);
- err = MPI_Send(msg, length, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
- if (err != MPI_SUCCESS) {
- printf("Process %i: Error in MPI_Send!\n", id);
- }
- }
- void mpi_recv_msg(){
- int length;
- MPI_Get_processor_name(msg, &length);
- err = MPI_Recv(msg, 80, MPI_CHAR, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, \
- &status);
- if (err != MPI_SUCCESS) {
- printf("Error in MPI_Recv!\n");
- }
- source_id = status.MPI_SOURCE;
- printf("Hello World from process %d running on %s\n", source_id, msg);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement