How to set thread priority in Linux?
In Linux, the priority of a thread can be set by calling the function pthread_setschedparam(). This function takes three parameters: the thread identifier, the scheduling policy, and the priority.
There are several types of scheduling strategies, including:
- SCHED_FIFO: First In First Out scheduling policy, where the thread with the highest priority will continue running until it voluntarily releases the CPU.
- SCHED_RR: A round-robin scheduling strategy where threads with higher priority run for a period of time before switching to the next thread of the same priority.
- SCHED_OTHER: Standard scheduling policy.
The range of priority levels is usually between 0-99, with smaller numbers indicating higher priority. It is important to note that in Linux, only privileged processes (such as the root user) can set higher priorities.
Here is an example of code for setting thread priority:
#include <pthread.h>
int main() {
pthread_t thread;
pthread_attr_t attr;
struct sched_param param;
pthread_attr_init(&attr);
// 设置线程调度策略为SCHED_FIFO
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
// 设置线程优先级为50
param.sched_priority = 50;
pthread_attr_setschedparam(&attr, ¶m);
// 创建线程并设置属性
pthread_create(&thread, &attr, myThreadFunction, NULL);
pthread_join(thread, NULL);
pthread_attr_destroy(&attr);
return 0;
}
In the above code, the thread’s scheduling policy is set to SCHED_FIFO and priority is set to 50 using the pthread_attr_setschedparam() function. When creating the thread, the preset attributes are used to give the thread the specified priority.
Please be careful when setting thread priorities, as setting them too high may lead to system instability or deadlocks.