C++多线程,为线程绑定cpu

文章目录

  • 1,使用
  • 2,函数

1,使用

set_cpu("detector", {0, 1, 2});

2,函数

void set_cpu(std::string thread_name, std::vector<short> cpu_ids) {
	int i, cpus = 0;
    cpu_set_t mask;
    cpu_set_t get;

    cpus = sysconf(_SC_NPROCESSORS_CONF);
    LOG(WARNING) << thread_name << " has " << cpus << " processor(s)";
    
    CPU_ZERO(&mask);
    for(auto id : cpu_ids) {
        CPU_SET(id, &mask);
    }

    /* 设置cpu 亲和性(affinity)*/
    if(pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
        LOG(ERROR) << thread_name << " set thread affinity faild";
    }
    else {
        LOG(WARNING) << thread_name << " set thread affinity successfully";
    }
    
    /* 查看cpu 亲和性(affinity)*/
    CPU_ZERO(&get);
    if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {
        LOG(ERROR) << thread_name << " get thread affinity failed";
    }   

    /* 查看当前线程所运行的所有cpu*/
    for (i = 0; i < cpus; i++) {
        if (CPU_ISSET(i, &get)) {
        	LOG(WARNING) << thread_name << " : " << (int)pthread_self()
                << " is running in processor " << i; 
        }   
    }   
    sleep(3); //查看
}

你可能感兴趣的:(C++,多线程)