RT-Thread 调度器钩子函数的使用

调度器钩子函数如何使用?

可以使用函数 rt_scheduler_sethook(scheduler_hook);来设置一个调度器钩子,括号里面的函数就是你自己的钩子函数。

现在写了一个例子:在钩子函数中打印线程切换的相关信息:

 
 /*
 * 在调度器钩子中打印线程切换信息
 */

#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)
{

    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 scheduler_hook(struct rt_thread* from, struct rt_thread* to)
{
    rt_kprintf("from: %s -->  to: %s \n", from->name , to->name);
}

int sch_hook_sample()
{   
    /* 设置调度器钩子 */
    rt_scheduler_sethook(scheduler_hook);
    
    /* 创建线程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(sch_hook_sample, sch_hook sample);

-----------------------

仿真运行结果:


 \ | /
- RT -     Thread Operating System
 / | \     3.1.0 build Aug 27 2018
 2006 - 2018 Copyright by rt-thread team
msh >sch_hook_sample 
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 
from: tidle -->  to: thread1 
thread 1 is running
from: thread1 -->  to: tidle 
from: tidle -->  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 

可以看到线程1 、2 、空闲线程之间的切换过程。

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nameless-Y

文章帮助到我了!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值