liunx 下线程优先级反转 的C语言使用示例
时间: 2024-10-20 13:05:50 浏览: 33
在Linux系统下,调整线程优先级通常使用`sched_setscheduler()`函数,而C语言标准库中的`pthread`库提供了相应的接口来操作线程调度。线程优先级反转是指原本高优先级的线程被切换到低优先级,而低优先级的线程获得更高的优先权。这里有一个简单的示例:
```c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
// 定义线程优先级枚举值
enum thread_priority {
LOW_PRIORITY = SCHED_YIELD,
HIGH_PRIORITY = SCHED_RR
};
// 高优先级任务函数
void high_priority_task(void* arg) {
pthread_attr_t attr;
pthread_attr_init(&attr);
// 设置高优先级
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedparam(&attr, THREAD_PRIORITY_POLICY, HIGH_PRIORITY);
while (true) {
printf("High priority task running\n");
sleep(1); // 模拟耗时任务
}
}
// 低优先级任务函数
void low_priority_task(void* arg) {
pthread_attr_t attr;
pthread_attr_init(&attr);
// 设置低优先级
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedparam(&attr, THREAD_PRIORITY_POLICY, LOW_PRIORITY);
while (true) {
printf("Low priority task running\n");
sched_yield(); // 切换当前进程让出CPU
sleep(1);
}
}
int main() {
pthread_t high_thread, low_thread;
// 创建并启动高优先级线程
if (pthread_create(&high_thread, NULL, high_priority_task, NULL)) {
perror("Failed to create high priority thread");
exit(EXIT_FAILURE);
}
// 创建并启动低优先级线程
if (pthread_create(&low_thread, NULL, low_priority_task, NULL)) {
perror("Failed to create low priority thread");
exit(EXIT_FAILURE);
}
// 等待两个线程结束
pthread_join(high_thread, NULL);
pthread_join(low_thread, NULL);
return 0;
}
阅读全文