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

北慕城南 提交于 2019-12-10 13:47:11

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8326427/how-to-force-a-c-program-to-run-on-a-particular-core

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!