面试题答案
一键面试- 头文件:
- 需要包含
<pthread.h>
用于线程相关操作,<sched.h>
用于设置线程优先级。
- 需要包含
- 函数:
pthread_setschedparam()
函数用于设置线程的调度参数,包括优先级。其原型为:
int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param);
- 其中
thread
是要设置优先级的线程标识符,policy
是调度策略(如SCHED_FIFO
或SCHED_RR
),param
是一个指向struct sched_param
结构体的指针,该结构体包含优先级值。struct sched_param
中只有一个成员sched_priority
用于指定线程优先级。
- 示例代码片段:
#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, ¶m) != 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, ¶m) != 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权限运行等)。