Linux/Android NDK线程绑定

zhongzhiwei 2020-05-07

在线程中的设置代码如下,首先需要确保你是单个线程在跑!

void bind_to_cpu(int cpu_id) {
    int64_t cores = sysconf(_SC_NPROCESSORS_CONF);
    PRV_DPT_LOGI("CPUS:?%lu\n", cores);
    if(cpu_id>=cores) {
        PRV_DPT_LOGE("bind_to_cpu: assertion error!");
        return;
    }
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(cpu_id, &mask);
    if(sched_setaffinity(0, sizeof(mask), &mask)==-1) {
        PRV_DPT_LOGE("bind_to_cpu: failed to set affinity!");
        return;
    }
}


void set_thread_name(const char * name){
    prctl(PR_SET_NAME, name);
}


void *DepthPreview_Thread(void * parent){
    // bind this thread to given cpu
    set_thread_name("prv_dpt");
    cv::setNumThreads(1); // if you use opencv in android ndk
    bind_to_cpu(0);
    // some other code here 
}

查看对应线程的cpu占用方法如下:
adb shell top -p [线程所属进程的pid,如相机进程就是camerahalserver的pid,也是通过top命令查看] -H | [findstr/grep] [线程名称,采用prctl设置线程名称]

相关推荐