fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <mpi.h>
  4.  
  5. #define ARRAY_SIZE 100
  6. #define MASTER_RANK 0
  7.  
  8. void compute_task(int *array, int size) {
  9. // Example computation: doubling each element of the array
  10. for (int i = 0; i < size; i++) {
  11. array[i] *= 2;
  12. }
  13. }
  14.  
  15. int main(int argc, char *argv[]) {
  16. int num_procs, rank;
  17. int array[ARRAY_SIZE];
  18.  
  19. MPI_Init(&argc, &argv);
  20. MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
  21. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  22.  
  23. // If master process
  24. if (rank == MASTER_RANK) {
  25. // Initialize array with some values
  26. for (int i = 0; i < ARRAY_SIZE; i++) {
  27. array[i] = i;
  28. }
  29.  
  30. // Distribute the array to other processes
  31. MPI_Bcast(array, ARRAY_SIZE, MPI_INT, MASTER_RANK, MPI_COMM_WORLD);
  32. } else {
  33. // Receive the array from master process
  34. MPI_Bcast(array, ARRAY_SIZE, MPI_INT, MASTER_RANK, MPI_COMM_WORLD);
  35. }
  36.  
  37. // Divide the computation among processes
  38. int chunk_size = ARRAY_SIZE / num_procs;
  39. int start_index = rank * chunk_size;
  40. int end_index = start_index + chunk_size;
  41.  
  42. // Perform computation on local portion of the array
  43. compute_task(array + start_index, chunk_size);
  44.  
  45. // Gather results back to master process
  46. MPI_Gather(array + start_index, chunk_size, MPI_INT, array, chunk_size, MPI_INT, MASTER_RANK, MPI_COMM_WORLD);
  47.  
  48. // Print results from master process
  49. if (rank == MASTER_RANK) {
  50. printf("Computed array:\n");
  51. for (int i = 0; i < ARRAY_SIZE; i++) {
  52. printf("%d ", array[i]);
  53. }
  54. printf("\n");
  55. }
  56.  
  57. MPI_Finalize();
  58.  
  59. return 0;
  60. }
  61.  
Success #stdin #stdout #stderr 0.31s 40660KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "void compute_task"
Execution halted