misteryes misteryes - 1 month ago 23
C Question

How to program so that different processes run on different CPU cores?

I'm writing a linux C program with 2 processes. I will run the program on different machines.

These machine may have multiple CPU cores.

When I run the program, will the system allocate different CPU core for different processes? or I need to write some codes so as to fully utilize the CPU cores?

Answer

If you wish to pin threads/processes to specific CPUs then you have to use the sched_setaffinity(2) system call or the pthread_setaffinity_np(3) library call for that. Each core in Linux has it's own virtual CPU ID.

These calls allow you to set the allowed CPU mask.

Otherwise it will be up to the digression of the scheduler to run your threads where it feels like running them.

Neither will guarantee that your process runs in parallel though. This is something only the scheduler can decide unless you run realtime.

Here is some sample code:

#include <sched.h>

int run_on_cpu(int cpu) {

    cpu_set_t allcpus;

    CPU_ZERO(&allcpus);
    sched_getaffinity(0, sizeof(cpu_set_t), &allcpus);

    int num_cpus = CPU_COUNT(&allcpus);

    fprintf(stderr, "%d cpus available for scheduling\nAvailable CPUs: ", num_cpus);

    size_t i;
    for (i = 0; i < CPU_SETSIZE; i++) {
        if (CPU_ISSET(i, &allcpus))
            fprintf(stderr, "%zu, ", i);
    }
    fprintf(stderr, "\n");

    if (CPU_ISSET(cpu, &allcpus)) {
        cpu_set_t cpu_set;
        CPU_ZERO(&cpu_set);
        CPU_SET(cpu, &cpu_set);
        return pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set);
    }

    return -1;
}