cprocesscpu-cores

how to force a c program to run on a particular core


Say I have the following c program:

#include <stdio.h>

int main()
{
    printf("Hello world \n");
    getchar();

    return 0;
}

gcc 1.c -o helloworld

and, say I have a dual core machine:

cat /proc/cpuinfo | grep processor | wc -l

Now my question is, when we execute the program, how do we force this program to run in core-0 (or any other particular core)?

How to do this programmatically? examples, api's, code reference would be helpful.

If there is no api's available then is there any compile time, link time, load time way of doing this?

OTOH, how to check whether a program is running in core-0 or core-1 (or any other core)?


Solution

  • Since you are talking about /proc/cpu, I assume you are using linux. In linux you would use the sched_setaffinity function. In your example you would call

    cpu_set_t set;
    CPU_ZERO(&set);        // clear cpu mask
    CPU_SET(0, &set);      // set cpu 0
    sched_setaffinity(0, sizeof(cpu_set_t), &set);  // 0 is the calling process
    

    Look up man sched_setaffinity for more details.