问题
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