krz*_*iek 5 concurrency java-native-interface multithreading android android-ndk
我正在尝试为Android编写代码,它会给我一些处理器的信息(id?)和运行线程的核心.
我已经谷歌和grep'ed一些灵感的来源,但没有运气.我所知道的是,我很可能需要一些C/C++调用.
我的工作如下:
#include <jni.h>
int getCpuId() {
// missing code
return 0;
}
int getCoreId() {
// missing code
return 0;
}
JNIEXPORT int JNICALL Java_com_spendoptima_Utils_getCpuId(JNIEnv * env,
jobject obj) {
return getCpuId();
}
JNIEXPORT int JNICALL Java_com_spendoptima_Utils_getCoreId(JNIEnv * env,
jobject obj) {
return getCoreId();
}
Run Code Online (Sandbox Code Playgroud)
整个项目编译并运行得很好.我能够从Java中调用函数,并得到正确的响应.
在这里有谁可以填补空白?
这似乎对我有用:
//...
#include <sys/syscall.h>
//...
int getCpuId() {
unsigned cpu;
if (syscall(__NR_getcpu, &cpu, NULL, NULL) < 0) {
return -1;
} else {
return (int) cpu;
}
}
//...
Run Code Online (Sandbox Code Playgroud)
好消息是,Android 上定义了必要的库和系统调用(sched_getcpu()和__getcpu())。坏消息是,它们不是 NDK 的一部分。
您可以使用此答案中显示的方法来滚动您自己的系统调用包装器和库调用。
另一种方法是读取/proc/self/stat并解析该processor条目。proc (5) 手册页描述了该格式:
Run Code Online (Sandbox Code Playgroud)/proc/[pid]/stat Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c. ... processor %d (since Linux 2.2.8) CPU number last executed on.
这要慢得多,并且如果更新内核,“文件”格式可能会改变,所以这不是推荐的方法。