欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > linux 进程/线程设置核亲和性

linux 进程/线程设置核亲和性

2025/5/15 1:28:38 来源:https://blog.csdn.net/qq_40008325/article/details/147001660  浏览:    关键词:linux 进程/线程设置核亲和性

1,线程绑定内核

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

// 定义一个函数,用于设置线程的CPU亲和性
void set_thread_affinity(pthread_t thread, int cpu_id) {
    cpu_set_t cpuset;
    int s;

    // 清空CPU集合并添加指定的CPU
    CPU_ZERO(&cpuset);
    CPU_SET(cpu_id, &cpuset);

    // 设置线程的CPU亲和性
    s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
    if (s != 0) {
        perror("pthread_setaffinity_np");
        exit(EXIT_FAILURE);
    }

    // 验证设置是否成功
    s = pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
    if (s != 0) {
        perror("pthread_getaffinity_np");
        exit(EXIT_FAILURE);
    }

    // 打印CPU亲和性设置结果
    for (int i = 0; i < CPU_SETSIZE; i++) {
        if (CPU_ISSET(i, &cpuset)) {
            printf("Thread %lu is running on CPU %d\n", thread, i);
        }
    }
}

// 线程函数
void* thread_function(void* arg) {
    // 设置本线程的CPU亲和性到CPU 0
    set_thread_affinity(pthread_self(), 0);

    // 执行线程的工作...
    return NULL;
}

int main() {
    pthread_t thread;

    // 创建线程
    if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
        perror("pthread_create");
        return 1;
    }

    // 等待线程结束
    if (pthread_join(thread, NULL) != 0) {
        perror("pthread_join");
        return 1;
    }

    return 0;
}

设置本线程的CPU亲和性到CPU 0使用的函数是 set_thread_affinity(pthread_self(), 0),使用CPU_ZEROCPU_SET宏来初始化一个CPU集合并设置亲和性掩码。

 2,进程绑定内核,绑定某个进程到某一个核(核亲和性)

#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>

int main() {
    cpu_set_t cpuset;
    pid_t pid;

    // 获取当前进程的PID
    pid = getpid();

    // 清空CPU集合并设置亲和性掩码
    CPU_ZERO(&cpuset);
    // 假设我们要绑定到第0个CPU核心上
    CPU_SET(0, &cpuset);

    // 设置当前进程的CPU亲和性
    if (sched_setaffinity(pid, sizeof(cpuset), &cpuset) == -1) {
        perror("sched_setaffinity");
        exit(EXIT_FAILURE);
    }

    // 打印进程ID和设置的CPU亲和性
    printf("Process %d bound to CPU %d\n", pid, 0);

    // 为了演示效果,让进程睡眠一段时间
    sleep(60);

    return EXIT_SUCCESS;
}

查看绑定效果,taskset -p <PID>

taskset -p 688

pid 688's current affinity mask: 1

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词