首先有俩个思路,第一种提高这个进程的优先级,使CPU全速运行这个进程,这个是随机分配到某个CPU上,运行
函数原型:
#include
#include
int test1(const int pri)
{
struct sched_param sched ;
memset (&sched, 0, sizeof(sched)) ;
if (pri > sched_get_priority_max (SCHED_RR))
sched.sched_priority = sched_get_priority_max (SCHED_RR) ;
else
sched.sched_priority = pri ;
return sched_setscheduler (0, SCHED_RR, &sched) ;
}
pri= 0 (默认) to 99 (最高)
返回 0,成功; -1, 失败;
函数只需要放在程序的初始化位子,就行;
第二种
将树莓派单独预留出一个CPU,单独的运行这个实时的进程
首先在/boot/cmdline.txt 中末尾添加
isolcpus=x,x为屏蔽的核心 X=3时为树莓派中的最后一个CPU
然后将程序挂载在刚刚禁用的CPU上,使CPU全速运行这个程序
#define __USE_GNU
#include .h>
void test2(){
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(3,&mask);
if (sched_setaffinity(0,sizeof(mask),&mask)<0){
printf("affinity set fail!");}
}
这里需要定义 __USE_GNU
在 sched.h中(片断截取)
#ifdef __USE_GNU
/* Access macros for `cpu_set'. */
# define CPU_SETSIZE __CPU_SETSIZE
# define CPU_SET(cpu, cpusetp) __CPU_SET_S (cpu, sizeof (cpu_set_t), cpusetp)
# define CPU_CLR(cpu, cpusetp) __CPU_CLR_S (cpu, sizeof (cpu_set_t), cpusetp)
# define CPU_ISSET(cpu, cpusetp) __CPU_ISSET_S (cpu, sizeof (cpu_set_t), \
cpusetp)
# define CPU_ZERO(cpusetp) __CPU_ZERO_S (sizeof (cpu_set_t), cpusetp)
# define CPU_COUNT(cpusetp) __CPU_COUNT_S (sizeof (cpu_set_t), cpusetp)
# define CPU_SET_S(cpu, setsize, cpusetp) __CPU_SET_S (cpu, setsize, cpusetp)
# define CPU_CLR_S(cpu, setsize, cpusetp) __CPU_CLR_S (cpu, setsize, cpusetp)
# define CPU_ISSET_S(cpu, setsize, cpusetp) __CPU_ISSET_S (cpu, setsize, \
cpusetp)
# define CPU_ZERO_S(setsize, cpusetp) __CPU_ZERO_S (setsize, cpusetp)
# define CPU_COUNT_S(setsize, cpusetp) __CPU_COUNT_S (setsize, cpusetp)
# define CPU_EQUAL(cpusetp1, cpusetp2) \
__CPU_EQUAL_S (sizeof (cpu_set_t), cpusetp1, cpusetp2)
# define CPU_EQUAL_S(setsize, cpusetp1, cpusetp2) \
__CPU_EQUAL_S (setsize, cpusetp1, cpusetp2)
# define CPU_AND(destset, srcset1, srcset2) \
__CPU_OP_S (sizeof (cpu_set_t), destset, srcset1, srcset2, &)
# define CPU_OR(destset, srcset1, srcset2) \
__CPU_OP_S (sizeof (cpu_set_t), destset, srcset1, srcset2, |)
# define CPU_XOR(destset, srcset1, srcset2) \
__CPU_OP_S (sizeof (cpu_set_t), destset, srcset1, srcset2, ^)
# define CPU_AND_S(setsize, destset, srcset1, srcset2) \
__CPU_OP_S (setsize, destset, srcset1, srcset2, &)
# define CPU_OR_S(setsize, destset, srcset1, srcset2) \
__CPU_OP_S (setsize, destset, srcset1, srcset2, |)
# define CPU_XOR_S(setsize, destset, srcset1, srcset2) \
__CPU_OP_S (setsize, destset, srcset1, srcset2, ^)
# define CPU_ALLOC_SIZE(count) __CPU_ALLOC_SIZE (count)
# define CPU_ALLOC(count) __CPU_ALLOC (count)
# define CPU_FREE(cpuset) __CPU_FREE (cpuset)
/* Set the CPU affinity for a task */
extern int sched_setaffinity (__pid_t __pid, size_t __cpusetsize,
const cpu_set_t *__cpuset) __THROW;
/* Get the CPU affinity for a task */
extern int sched_getaffinity (__pid_t __pid, size_t __cpusetsize,
cpu_set_t *__cpuset) __THROW;
#endif
所以想使用挂载在CPU上的函数的时候,需要定义 __USE_GNU,也同样的只需要在程序初始化的时候,添加就可以了
俩者也可以同时添加在一起。