C\C++实现CPU核上绑定固定线程

 参考文章:Linux中线程与CPU核的绑定_bluenet13的博客-CSDN博客

long sysconf(int name);

函数sysconf获取运行时的系统配置信息

设置线程亲和性,将线程绑定到指定CPU核

int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize,const cpu_set_t *cpuset);

thread:线程id

cpusetsize:集合内存大小

cpuset:CPU核的集合

获取指定线程的CPU集合

int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t *cpuset);

thread:线程id

cpusetsize:集合内存大小

cpuset:CPU核的集合

对CPU核的集合操作

void CPU_ZERO (cpu_set_t *set); //初始化,设为空

void CPU_SET (int cpu, cpu_set_t *set); //将某个cpu加入cpu集中

void CPU_CLR (int cpu, cpu_set_t *set); //将某个cpu从cpu集中移出

int CPU_ISSET (int cpu, const cpu_set_t *set); //判断某个cpu是否已在cpu集中设置了

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>

void *myfun(void *arg)
{
    cpu_set_t mask;
    cpu_set_t get;
    char buf[256];
    int i;
    int j;
    int num = sysconf(_SC_NPROCESSORS_CONF); // 在运行时获取配置信息,获取CPU核个数
    CPU_ZERO(&mask);    // 初始化,设为空
    printf("system has %d processor(s)\n", num);
    for(i = 0; i < num; i++){
        CPU_SET(i, &mask);  // 将某个cpu加入cpu集中 
    }
    // 将线程绑定到cpu集中的各个CPU核,这样做不太好,会导致线程在各CPU核中切换,导致性能下降
    // 本次只为测试
    if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
        fprintf(stderr, "set thread affinity failed\n");
    }
    CPU_ZERO(&get);
    if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {
        fprintf(stderr, "get thread affinity failed\n");
    } 
    for (i = 0; i < num; i++) {
        if (CPU_ISSET(i, &get)) {
            printf("thread %ld is running in processor %d\n", pthread_self(), i);
        }
        j = 0;
        while (j++ < 100000000){
            memset(buf, 0, sizeof(buf));
        }
    }
    pthread_exit(NULL);
}
int main(){
    int num = sysconf(_SC_NPROCESSORS_CONF);
    printf("CPU核数:%d \n", num);
    pthread_t tid;
    if (pthread_create(&tid, NULL, myfun, NULL) != 0) {
        fprintf(stderr, "thread create failed\n");
        return -1;
    }
    pthread_join(tid, NULL);
    return 0;
}

在终端执行操作:

[root@chen02 CPUBind]# g++ -o cpu CPU_Bind.cpp -lpthread

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值