Guest User

Untitled

a guest
Oct 15th, 2025
27
0
153 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | Source Code | 0 0
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sched.h>
  6. #include <mpi.h>
  7. #include <omp.h>
  8.  
  9. /*
  10.   Compile:
  11.     mpicc -fopenmp -O2 -o mpi_openmp_core_info mpi_openmp_core_info.c
  12.  
  13.   Run (example):
  14.     mpirun -np 4 ./mpi_openmp_core_info 4
  15.     # -> 4 MPI ranks, each spawns 4 OpenMP threads
  16. */
  17.  
  18. int main(int argc, char **argv) {
  19.     int required = MPI_THREAD_FUNNELED;
  20.     int provided;
  21.     MPI_Init_thread(&argc, &argv, required, &provided);
  22.  
  23.     int world_rank, world_size;
  24.     MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  25.     MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  26.  
  27.     int num_threads = 1;
  28.     if (argc >= 2) num_threads = atoi(argv[1]);
  29.     if (num_threads <= 0) num_threads = 1;
  30.  
  31.     pid_t pid = getpid();
  32.  
  33.     printf("[Rank %d] PID %d starting, total ranks = %d, OpenMP threads = %d\n",
  34.            world_rank, pid, world_size, num_threads);
  35.     fflush(stdout);
  36.  
  37.     omp_set_num_threads(num_threads);
  38.  
  39. #pragma omp parallel
  40.     {
  41.         int tid = omp_get_thread_num();
  42.         int cpu = sched_getcpu();
  43.  
  44. #pragma omp critical
  45.         {
  46.             printf("[Rank %d] PID %d | Thread %d/%d | Running on core %d\n",
  47.                    world_rank, pid, tid, omp_get_num_threads(), cpu);
  48.             fflush(stdout);
  49.         }
  50.     }
  51.  
  52.     MPI_Barrier(MPI_COMM_WORLD);
  53.     if (world_rank == 0) {
  54.         printf("All ranks finished.\n");
  55.     }
  56.  
  57.     MPI_Finalize();
  58.     return 0;
  59. }
Tags: MPI
Advertisement
Add Comment
Please, Sign In to add comment