您的位置:首页 > 编程语言

多线程编程中,将线程绑定到指定CPU

2012-08-10 16:20 197 查看
参考网络上的资料,具体出处忘了,亲测可以

在多核处理上,处理大数据业务时,有时为了对线程资源有更好的控制,需要将一些核心处理线程绑定到指定的CPU核上,pthread库就提供这样的接口。

大概封装了一下,在线程函数中调用就可以了

int bind2cpu(int cpu_index)
{
cpu_set_t set;
cpu_set_t get;
int cpu_num = sysconf(_SC_NPROCESSORS_CONF);
if(cpu_index >= cpu_num)
return -1;

CPU_ZERO(&set);
CPU_SET(cpu_index, &set);
if (pthread_setaffinity_np(pthread_self(), sizeof(set), &set) < 0) {
perror( "set thread affinity failed");
return -2;
}
#if 1
CPU_ZERO(&get);
if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {
perror("get thread affinity failed");
return -3;
}
int j;

for (j = 0; j < cpu_num; j++) {
if (CPU_ISSET(j, &get)) {
printf("the thread is running in processor %d\n", j);
}
}
#endif
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: