参考链接:
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集中移出