在Linux操作系统中,pthread_create函数本身不支持直接设置线程优先级
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
int setThreadPriority(pthread_t thread, int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, ¶m) != 0) {
perror("Error setting thread priority");
return -1;
}
return 0;
}
main函数中创建线程并设置优先级:int main() {
pthread_t thread;
int priority = 99; // 设置线程优先级,范围通常为1到99,数值越大优先级越高
if (setThreadPriority(thread, priority) == -1) {
exit(EXIT_FAILURE);
}
// 在这里创建你的线程
// ...
return 0;
}
请注意,不是所有的调度策略都支持优先级设置。例如,SCHED_IDLE和SCHED_BATCH等策略不支持优先级设置。另外,设置线程优先级可能会导致系统资源争用,因此请谨慎使用。