Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

process

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)?

like image 970
Sangeeth Saravanaraj Avatar asked Nov 30 '11 13:11

Sangeeth Saravanaraj


2 Answers

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.

like image 181
Gunther Piez Avatar answered Nov 01 '22 11:11

Gunther Piez


This is OS-specific. As Felice points out, you can do it on Linux by calling sched_setaffinity in your program. If you end up running on multiple platforms, though, you'll have to code something different for each.

Alternatively, you can specify the affinity when you launch your executable, from the command line or a run script or whatever. See taskset for a Linux command-line tool to do this.

like image 30
Useless Avatar answered Nov 01 '22 10:11

Useless