是否可以在 Android 中使用 sched_setaffinity 设置亲和力? [英] Is it possible to set affinity with sched_setaffinity in Android?
问题描述
是否可以在使用 Android NDK 编译的本机 C 代码中设置 CPU 亲和性?由于系统使用的是 Linux 内核,应该可以使用 sched_setaffinity/sched_getaffinity 函数,但是当我使用 NDK 编译时,我收到错误消息,抱怨 cpu_set_t 类型未知(用作函数的参数).有没有其他方法可以做到这一点?当我使用 CodeSourcerys ARM 编译器 (arm-none-linux-gnueabi-gcc) 进行编译时,这似乎不是问题,因此系统显然支持所需的系统调用.
Is it possible to set CPU affinity in native C code compiled with the Android NDK? Since the system is using a Linux kernel, it should be possible to use the sched_setaffinity/sched_getaffinity functions, but when I compile with the NDK, I get errors complaining that the cpu_set_t type is unknown (which is used as an argument to the functions). Is there any other way to accomplish this? When I compile with CodeSourcerys ARM compiler (arm-none-linux-gnueabi-gcc) this does not seem to be a problem, so the system obviously supports the required syscalls.
推荐答案
以下代码适用于 NDK r5 或更高版本:
The following code works well with NDK r5 or newer:
#include <sys/syscall.h>
#include <pthread.h>
void setCurrentThreadAffinityMask(int mask)
{
int err, syscallres;
pid_t pid = gettid();
syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallres)
{
err = errno;
LOGE("Error in the syscall setaffinity: mask=%d=0x%x err=%d=0x%x", mask, mask, err, err);
}
}
这篇关于是否可以在 Android 中使用 sched_setaffinity 设置亲和力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!