Linux 线程优先级设置(内含C语言版线程创建、绑定CPU和优先级设置代码)

本文介绍了Linux中线程的创建、优先级设定和CPU绑定。线程创建使用pthread_create,通过pthread_attr_t结构体调整线程优先级,如SCHED_OTHER、SCHED_FIFO和SCHED_RR。线程优先级设置需要超级用户权限,并通过sched_param结构体设置。同时,展示了如何用C语言实现线程与特定CPU核的绑定。
摘要由CSDN通过智能技术生成

参考链接:
https://blog.csdn.net/wushuomin/article/details/80051295 //详细讲解pthread_create 函数
https://blog.csdn.net/heybeaman/article/details/90896663 //讲解pthread_join的使用
https://blog.csdn.net/tiger_ibm/article/details/7932386 //线程优先级设定

1 线程创建

线程创建使用的函数接口为:pthread_create()
函数原型如下:

#include <pthread.h>
int pthread_create(
                 pthread_t *restrict tidp,   //新创建的线程ID指向的内存单元。
                 const pthread_attr_t *restrict attr,  //线程属性,默认为NULL
                 void *(*start_rtn)(void *), //新创建的线程运行的函数
                 void *restrict arg //默认为NULL。如果线程运行的函数需要参数,将参数放入结构中并将地址作为arg传入。
                );

2 线程优先级设定

线程优先级可以由线程属性控制,linux 内核提供了很多函数操作 pthread_attr_t 结构体,修改后将该结构体 通过 函数pthread_create 的第二个参数传递给线程即可。

//线程调度策略设置和获取函数,pthread_attr_t 为线程属性, policy 就是 线程调度策略
int pthread_attr_setschedpolicy(pthread_attr_*, int policy)
int pthread_attr_getschedpolicy(const pthread_attr_t *, int * policy)

SCHED_OTHER(0):分时调度策略,线程默认调度策略,不区分优先级,该调度方式通过分时来完成的。当线程处于这种调度策略的时候,对线程进行优先级设置会失败。但高优先级的线程可以抢占处于该调度策略的线程。
SCHED_FIFO(1):实时调度策略,先进先出原则,这种调度方式有优先级之分,并且无时间片概念,处于该调度策略时,高优先级的进程将会一直占用CPU 直到有更高优先级的线程出现,将线程设置为该调度策略的时候需要超级用户模式。
SCHED_RR(2):实时调度策略,在SCHED_FIFO的基础上加入了时间片。于FIFO 不同,FIFO 即使有相同优先级的线程,也必须等到当前线程运行完毕后才能执行,RR可以使 相同优先级的线程都运行一段时间。

//线程优先级设置和获取函数
int pthread_attr_setschedparam(pthread_attr_t *,const struct sched_param *);
int pthread_attr_getschedparam(const pthread_attr_t *,struct sched_param *);

结构体 sched_param 中 只有一项 __sched_priority 代表优先级,值越大优先级越高。

//获取系统调度策略的最大最小优先级
int sched_get_priority_max( int policy );
int sched_get_priority_min( int policy );
//获取和设置线程的继承性 默认是 PTHREAD_INHERIT_SCHED 
int pthread_attr_getinheritsched(const pthread_attr_t * attr,int *inheritsched);
int pthread_attr_setinheritsched(pthread_attr_t * attr,int inheritsched);

3 线程绑定CPU


int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize,const cpu_set_t *cpuset);
int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t *cpuset);
从函数名以及参数名都很明了,唯一需要点解释下的可能就是cpu_set_t这个结构体了。这个结构体的理解类似于select中的fd_set,可以理解为cpu集,也是通过约定好的宏来进行清除、设置以及判断:
//初始化,设为空
void CPU_ZERO (cpu_set_t *set); 
//将某个cpu加入cpu集中 
void CPU_SET (int cpu, cpu_set_t *set); 
//将某个cpu从cpu集中移出 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值