在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
等策略不支持优先级设置。另外,设置线程优先级可能会导致系统资源争用,因此请谨慎使用。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>