linux下可以直接调用pthread_setaffinity_np,将当前线程绑定在具体的cpu上,而android该API被屏蔽了,需要调用sched这个系统API,详情见下面代码:
package nativelibs;
public class Affinity {
static {
System.loadLibrary("Affinity");
}
public static native void bindToCpu(int cpu);
}
void set_cur_thread_affinity(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, err=%d",mask,errno);
}
LOGD("tid = %d has setted affinity success",pid);
}
ok,具体的JNI代码如下:
#include <jni.h>
#include <android/log.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/syscall.h>
#define TAG "Affinity"
#define DEBUG 1
#ifndef CPU_ZERO
#define CPU_SETSIZE 1024
#define __NCPUBITS (8 * sizeof (unsigned long))
typedef struct
{
unsigned long __bits[CPU_SETSIZE / __NCPUBITS];
} cpu_set_t;
#define CPU_SET(cpu, cpusetp) \
((cpusetp)->__bits[(cpu)/__NCPUBITS] |= (1UL << ((cpu) % __NCPUBITS)))
#define CPU_ZERO(cpusetp) \
memset((cpusetp), 0, sizeof(cpu_set_t))
#else
#define CPU_SET(cpu,cpustep) ((void)0)
#define CPU_ZERO(cpu,cpustep) ((void)0)
#endif
#ifdef DEBUG
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)
#else
#define LOGD(...) ((void)0)
#define LOGE(...) ((void)0)
#endif
void set_cur_thread_affinity(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, err=%d",mask,errno);
}
LOGD("tid = %d has setted affinity success",pid);
}
static int getCores() {
return sysconf(_SC_NPROCESSORS_CONF);
}
JNIEXPORT int JNICALL Java_nativelibs_Affinity_getCores(JNIEnv *env, jclass type) {
return getCores();
}
JNIEXPORT void JNICALL Java_nativelibs_Affinity_bindToCpu(JNIEnv *env, jclass type, jint cpu) {
int cores = getCores();
LOGD("get cpu number = %d\n",cores);
if (cpu >= cores) {
LOGE("your set cpu is beyond the cores,exit...");
return;
}
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpu,&mask);
set_cur_thread_affinity((int)(&mask));
LOGD("set affinity to %d success",cpu);
}