Reputation: 75555
I am currently using sched_setaffinity
to pin a thread to a particular CPU core.
void setCpuAffinity(int id) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(id, &cpuset);
assert(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0);
}
Unfortunately, I cannot find a corresponding function to unpin the thread from any given core, and allow the kernel to schedule the thread on any core.
How can I reverse the effect of CPU pinning and allow free movement of a thread once again?
I am aware that one hack would be to use CPU_OR
and add every CPU ID to the allowable set, but I am looking for a less hacky approach that restores the state of a thread to the state before sched_setaffinity
was ever called.
Upvotes: 0
Views: 600
Reputation: 75555
Using @phs's suggestion, I wrote the following two functions, which are called before and after cpu pinning to unpin the thread. This successfully unpins the CPU.
void setCpuAffinity(cpu_set_t cpuset) {
assert(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0);
}
cpu_set_t getCpuAffinity() {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
assert(sched_getaffinity(0, sizeof(cpuset), &cpuset) == 0);
return cpuset;
}
Upvotes: 1