Rtthread学习笔记(一)空闲线程钩子函数

有活干活,没事学点,记录笔记方便查看。

一、空闲线程钩子函数

空闲钩子函数是空闲线程的钩子函数,如果设置了空闲钩子函数,就可以在系统执行空闲线程时,自动执行空闲钩子函数来做一些其他事情,比如系统指示灯、功耗管理、看门狗喂狗、CPU使用率。可以设置4个空闲钩子函数。

设置 / 删除空闲钩子的接口如下:
rt_err_t rt_thread_idle_sethook(void (*hook)(void));
rt_err_t rt_thread_idle_delhook(void (*hook)(void));

二、调度器钩子函数

在整个系统的运行时,系统都处于线程运行、中断触发 - 响应中断、切换到其他线程,甚至是线程间的切换过程中,或者说系统的上下文切换是系统中最普遍的事件。有时用户可能会想知道在一个时刻发生了什么样的线程切换,可以通过调用下面的函数接口设置一个相应的钩子函数。只能设置1个调度钩子函数,在系统线程切换时,这个钩子函数将被调用:
void rt_scheduler_sethook(void (hook)(struct rt_thread from, struct rt_thread* to));
在这里插入图片描述

#include <rtthread.h>
#define THREAD_STACK_SIZE 1024
#define THREAD_PRIORITY 20
#define THREAD_TIMESLICE 10
/* 针 对 每 个 线 程 的 计 数 器 */
volatile rt_uint32_t count[2];
/* 线 程 1、2 共 用 一 个 入 口, 但 入 口 参 数 不 同 */
static void thread_entry(void* parameter) {
rt_uint32_t value;
value = (rt_uint32_t)parameter;
while (1)
{
rt_kprintf("thread %d is running\n", value);
rt_thread_mdelay(1000); // 延 时 一 段 时 间 } }
static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;
static void hook_of_scheduler(struct rt_thread* from, struct rt_thread* to) {
rt_kprintf("from: %s --> to: %s \n", from->name , to->name);
}
int scheduler_hook(void) {
/* 设 置 调 度 器 钩 子 */
rt_scheduler_sethook(hook_of_scheduler);
/* 创 建 线 程 1 */
tid1 = rt_thread_create("thread1",
thread_entry, (void*)1,
THREAD_STACK_SIZE,
THREAD_PRIORITY, THREAD_TIMESLICE);
if (tid1 != RT_NULL)
rt_thread_startup(tid1);
/* 创 建 线 程 2 */
tid2 = rt_thread_create("thread2",
thread_entry, (void*)2,
THREAD_STACK_SIZE,
THREAD_PRIORITY,THREAD_TIMESLICE - 5);
if (tid2 != RT_NULL)
rt_thread_startup(tid2);
return 0;
}
/* 导 出 到 msh 命 令 列 表 中 */
MSH_CMD_EXPORT(scheduler_hook, scheduler_hook sample);

运行结果

\ | /
- RT - Thread Operating System
/ | \ 3.1.0 build Aug 27 2018
2006 - 2018 Copyright by rt-thread team
msh > scheduler_hook
msh >from: tshell --> to: thread1
thread 1 is running
from: thread1 --> to: thread2
thread 2 is running
from: thread2 --> to: tidle
from: tidle --> to: thread1
thread 1 is running
from: thread1 --> to: tidle
from: tidle --> to: thread2
thread 2 is running
from: thread2 --> to: tidle
…

由仿真的结果可以看出,对线程进行切换时,设置的调度器钩子函数是在正常工作的,一直在打印线程切换的信息,包含切换到空闲线程。

发布了11 篇原创文章 · 获赞 4 · 访问量 979

猜你喜欢

转载自blog.csdn.net/Davidysw/article/details/104817525
今日推荐