'How to detect whether a core has been bound in C/C++?
I coded a program that needs to run independently on a core to gain high performance. And, I need to run multiple such programs on a single machine.
So, I would like to know is there a way to detect whether a core is bound or not.
With that, a program can attempt to bind from core 0 and try the next one if it finds that the core is already bound.
I tried to use sched_setaffinity()
to get exclusive access on a core.
But it seems not to work.
Here is my code:
#define _GNU_SOURCE
#include <assert.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void print_affinity() {
cpu_set_t mask;
long nproc, i;
if (sched_getaffinity(0, sizeof(cpu_set_t), &mask) == -1) {
perror("sched_getaffinity");
assert(false);
}
nproc = sysconf(_SC_NPROCESSORS_ONLN);
printf("sched_getaffinity = ");
for (i = 0; i < nproc; i++) {
printf("%d ", CPU_ISSET(i, &mask));
}
printf("\n");
}
int main(void) {
cpu_set_t mask;
print_affinity();
printf("sched_getcpu = %d\n", sched_getcpu());
CPU_ZERO(&mask);
CPU_SET(0, &mask);
if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) == -1) {
perror("sched_setaffinity");
assert(false);
}
print_affinity();
printf("sched_getcpu = %d\n", sched_getcpu());
while(true){
}
return EXIT_SUCCESS;
}
I run the program in two terminals.
My expectation is that the first program will bind to core 0 while the second program will see the core 0 is bound (by calling sched_getaffinity
)
However, it seems that the second program can't be aware that core 0 is bound, i.e., the first print_affinity()
of the second program prints out that all bits of the CPU mask are 1.
Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|