pthread 调度与优先级设置
pthread_attr_setschedpolicy
-
函数原型:
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);
- attr:指向线程属性对象的指针。
- policy:要设置的调度策略。支持的调度策略为 SCHED_FIFO,SCHED_RR,SCHED_OTHER。
- 返回值:成功返回 0,失败返回错误代码。
-
用于指定线程的调度策略。
-
为了使
pthread_attr_setschedpolicy
生效,调用者必须在调用pthread_create
之前调用pthread_attr_setinheritsched
将attr
的继承属性设置为PTHREAD_EXPLICIT_SCHED
。
pthread_attr_setschedparam
-
函数原型:
int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param);
- attr:指向线程属性对象的指针。
- param:是一个指向 sched_param 结构体的指针,该结构体包含了要设置的优先级。
- 返回值:成功返回 0,失败返回错误代码。
-
用于指定线程的调度参数。
-
为了使
pthread_attr_setschedparam
生效,调用者必须在调用pthread_create
之前调用pthread_attr_setinheritsched
将attr
的继承属性设置为PTHREAD_EXPLICIT_SCHED
。
pthread_attr_setinheritsched
-
函数原型:
int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);
- attr:指向线程属性对象的指针。
- inheritsched:用于指定是否继承父线程的调度策略和优先级,可以使用以下两个值:
- PTHREAD_INHERIT_SCHED:表示线程将继承创建它的线程的调度策略和优先级。
- PTHREAD_EXPLICIT_SCHED:表示线程将使用自己在线程属性对象中设置的调度策略和优先级。
- 返回值:成功返回 0,失败返回错误代码。
-
用于设置线程属性对象是否继承父线程的调度策略和优先级。
pthread_setschedparam
-
函数原型:
int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param);
- thread:目标线程的标识符。
- policy: 要设置的调度策略,支持的调度策略为 SCHED_FIFO,SCHED_RR,SCHED_OTHER,SCHED_BATCH,SCHED_IDLE。
- param:是一个指向 sched_param 结构体的指针,该结构体包含了要设置的优先级。
- 返回值:成功返回 0,失败返回错误代码。
-
用于设置指定线程的调度参数,包括线程的优先级和调度策略。
pthread_setschedprio
-
函数原型:
int pthread_setschedprio(pthread_t thread, int prio);
- thread:目标线程的标识符。
- prio:要设置的线程优先级。
- 返回值:成功返回 0,失败返回错误代码。
-
用于设置指定线程的优先级。
示例 1
-
以 SCHED_FIFO 的方式调度线程,并设置其优先级为 5。
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sched.h> void *thread_func(void *arg) { usleep(10000); return NULL; } int main() { // 初始化线程属性对象 pthread_attr_t attr; pthread_attr_init(&attr); // 设置线程的调度策略 pthread_attr_setschedpolicy(&attr, SCHED_FIFO); // 设置线程的优先级 struct sched_param param; param.sched_priority = 5; pthread_attr_setschedparam(&attr, ¶m); // 设置线程不继承父进程调度策略以及优先级 pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); // 创建线程 pthread_t thread; pthread_create(&thread, &attr, thread_func, NULL); // 销毁线程属性对象 pthread_attr_destroy(&attr); // 等待线程结束 pthread_join(thread, NULL); return 0; }
示例 2
-
以 SCHED_IDLE 的方式调度线程。
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sched.h> void *thread_func(void *arg) { usleep(10000); return NULL; } int main() { // 创建线程 pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); // 设置线程的调度策略 struct sched_param param; param.sched_priority = 0; pthread_setschedparam(thread, SCHED_IDLE, ¶m); // 等待线程结束 pthread_join(thread, NULL); return 0; }