On a multi-core machine, why doesn’t the CPU automatically move a process to a new core if there are multiple processes all on the same core at full capacity?
Here is a sample program which reproduces the problem I’m seeing:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void RunClient(int i) {
printf("Starting client %d\n", i);
while (true) {
}
}
int main(int argc, char** argv) {
for (int i = 0; i < 4; ++i) {
pid_t p_id = fork();
sleep(3);
if (p_id == -1) {
perror("fork");
} else if (p_id == 0) {
RunClient(i);
exit(0);
}
}
return 0;
}
This works as expected (when I check top, I see all 4 processes are running at 100%).
However, if I remove the “sleep(3)” line, then sometimes multiple processes are set to the same CPU and thus not running at full capacity (for example, one process might be at 100% while the other 3 are each at 33%). What’s going on and how do I fix it?
I know I can manually set the CPU affinity, but that seems like a fragile solution?
This isn’t an issue with your code, it’s an issue with your OS scheduler. It works as expected for me (ubuntu 11.10) both with and without the
sleep(3)But +1 for posting an SSCCE