Search code examples
multithreadingparallel-processingmultiprocessingopenmpi

Forcing MPI to use a specified no. of cores


I am kinda new to MPI, so forgive me if it is a trivial question. I have a quad core CPU. And I want to run an OpenMPI C++ program that uses two processes on a single core. Is there any way to do so? If so, then how? I referred to this link on stack overflow which, most probably, says that there might be a way... If so, then how can I do it?


Solution

  • Since MPI spawns separate processes, the scheduling of processes onto cores is generally/usually performed by your operating system. You can still achieve what you want by manually setting the affinity of the processes to a specific core.

    You can do this in Linux using the sched_setaffinity function.

    To pin a process to a specific core, you can use the following approach:

    #include <mpi.h>
    #include <sched.h>
    
    // ...
    
    void pin_to_core(int cpuid) {                                            
        cpu_set_t set;                                                       
        CPU_ZERO(&set);                                                      
        CPU_SET(cpuid,&set);                                                                                                                                                                                                         
        sched_setaffinity(0,sizeof(cpu_set_t),&set);
    }
    
    // ....
    
    int main(int argc, char* argv[]) {
        MPI_Init(&argc, &argv);
        pin_to_core(0); // pin process to core 0
        // ...
        MPI_Finalize();
    }
    

    Make sure to call this function after you call MPI_Init in your main function and specify the core you want to pin the process to.