linux下进程与线程绑核

进程:调用sched_setaffinity

线程:调用pthread_setaffinity_np

int bind_to_core(int core)

{
    cpu_set_t cpu_set;
    int ret=0;
    pthread_t thread;
    
    if(core<0)
    {
        log_add(LOG_ERROR,"bind thread to core,invalid param.");
        return -1;
    }
    int num = sysconf(_SC_NPROCESSORS_CONF);

    /* bind to a cpu core. */
    CPU_ZERO(&cpu_set);
    CPU_SET(core,&cpu_set);


    thread=pthread_self();
    ret=pthread_setaffinity_np(thread,sizeof(cpu_set_t),&cpu_set);
    if(ret!=0)
    {
        log_add(LOG_ERROR,"set thread affinity failed. error:%d",ret);


        return -1;
    }
    
    log_add(LOG_DEBUG,"thread 0x%x bind to core %d",thread,core);


    return 0;
}

你可能感兴趣的:(linux下进程与线程绑核)