I want to set CPU affinity on an Android device, but when I attempt to run code on the middle or big cores, sched_setaffinity occasionally returns -1. How can I resolve this issue?
My Android device features a Snapdragon 888 CPU with 8 cores: 4 Cortex-A55s (1.8GHz, IDs: 0-3), 3 Cortex-A78s (2.42GHz, IDs: 4-6), and 1 Cortex-X1 (2.84GHz, ID: 7). The operating system is Android 11.
I want to set CPU affinity in my code. This is my function which sets the affinity:
inline int set_cpu(int core_id){
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(core_id,&mask);
int stat = sched_setaffinity(0,sizeof(cpu_set_t),&mask);
if (stat != 0){
std::cout << "Set CPU Affinity Failed! Errno " << errno << ": " << strerror(errno) << std::endl;
exit(1);
}
return stat;
}
And I call the function set_cpu like this:
void Myfunc(int core_id) {
set_cpu(core_id);
/* My code */
}
When I set core_id to values in {0,1,2,3}, it works fine. However, if I use core_id values from {4,5,6,7}, sched_setaffinity sometimes returns -1 with an "Invalid argument" error (Errno 22). In other words, the function is inconsistent with these values. (It seems that core 7 more often failed)
I'm unsure why this happens. How can I ensure the function works successfully every time?