MST
星途 面试题库

面试题:C语言中如何在Linux下初步设置CPU亲和性

请简述在Linux环境下,使用C语言设置CPU亲和性的基本步骤,并给出简单示例代码(假设只有一个线程,将其绑定到CPU 0)。
36.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

设置CPU亲和性基本步骤:

  1. 获取线程ID:使用pthread_self()函数获取当前线程的ID。
  2. 创建CPU亲和性掩码:使用cpu_set_t类型创建一个CPU亲和性掩码,并使用CPU_ZERO()宏初始化该掩码,然后使用CPU_SET()宏将需要绑定的CPU核心编号添加到掩码中。
  3. 设置CPU亲和性:使用pthread_setaffinity_np()函数将线程与设置好的CPU亲和性掩码进行绑定。

示例代码:

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

void* thread_function(void* arg) {
    cpu_set_t cpu_set;
    CPU_ZERO(&cpu_set);
    CPU_SET(0, &cpu_set);

    if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set) != 0) {
        perror("pthread_setaffinity_np");
    }

    printf("Thread is running on CPU: %d\n", sched_getcpu());
    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;
}