MST

星途 面试题库

面试题:C语言在Linux下如何设置多线程的基本优先级

在Linux环境中使用C语言编写多线程程序,简述如何设置线程的基本优先级,需要提及相关的头文件和函数,并给出一个简单示例代码片段展示如何设置线程优先级。
14.5万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 头文件
    • 需要包含 <pthread.h> 用于线程相关操作,<sched.h> 用于设置线程优先级。
  2. 函数
    • pthread_setschedparam() 函数用于设置线程的调度参数,包括优先级。其原型为:
    int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param);
    
    • 其中 thread 是要设置优先级的线程标识符,policy 是调度策略(如 SCHED_FIFOSCHED_RR),param 是一个指向 struct sched_param 结构体的指针,该结构体包含优先级值。struct sched_param 中只有一个成员 sched_priority 用于指定线程优先级。
  3. 示例代码片段
#include <pthread.h>
#include <stdio.h>
#include <sched.h>

void* thread_function(void* arg) {
    printf("Thread is running\n");
    return NULL;
}

int main() {
    pthread_t thread;
    struct sched_param param;
    int policy;

    // 创建线程
    if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
        printf("\n ERROR creating thread");
        return 1;
    }

    // 获取当前线程调度策略和参数
    if (pthread_getschedparam(thread, &policy, &param) != 0) {
        printf("\n ERROR getting scheduling policy");
        return 2;
    }

    // 设置优先级,假设使用SCHED_FIFO策略
    param.sched_priority = sched_get_priority_max(SCHED_FIFO);
    if (pthread_setschedparam(thread, SCHED_FIFO, &param) != 0) {
        printf("\n ERROR setting scheduling policy");
        return 3;
    }

    // 等待线程结束
    if (pthread_join(thread, NULL) != 0) {
        printf("\n ERROR joining thread");
        return 4;
    }

    return 0;
}

在上述代码中,首先创建了一个线程,然后获取该线程的调度策略和参数,接着设置线程优先级为 SCHED_FIFO 策略下的最大优先级,最后等待线程结束。注意,实际应用中需要根据具体需求合理选择调度策略和优先级值,并且在设置优先级时需要有足够的权限(如以root权限运行等)。