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

参考网络上的资料,具体出处忘了,亲测可以

在多核处理上,处理大数据业务时,有时为了对线程资源有更好的控制,需要将一些核心处理线程绑定到指定的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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值