【线程绑定cpu核心】

使用cat /proc/cpuinfo命令查询了自己设备的CPU

#ifndef _GNU_SOURCE
    #define _GNU_SOURCE
#endif
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>

void* thread_func(void* arg) {
    printf("Thread start.\n");

    // 绑定线程到第二个CPU核心上
    cpu_set_t cpu_set;
    CPU_ZERO(&cpu_set);
    CPU_SET(1, &cpu_set);
    pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set);

    // 执行线程任务
    while(1){
        std::cout<< "pthread" <<'\n';
        sleep(1);
    }
    printf("Thread end.\n");
    return NULL;
}

// g++ threadcpu.cpp -o threadcpu -lpthread -std=c++14
int main(int argc, char* argv[]) {
    // 创建线程
    pthread_t tid;
    int rc = pthread_create(&tid, NULL, thread_func, NULL);
    if (rc != 0) {
        perror("pthread_create");
        exit(EXIT_FAILURE);
    }

    // 等待线程执行完毕
    pthread_join(tid, NULL);

    return 0;
}

在这里插入图片描述
top -p 4078
【线程绑定cpu核心】_第1张图片
gdb threadcpu -p 4078
在这里插入图片描述

你可能感兴趣的:(c++,linux)