scheduler_hook.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-08-24 yangjie the first version
  9. */
  10. /*
  11. * 程序清单:调度器钩子
  12. * 在调度器钩子中打印线程切换信息
  13. */
  14. #include <rtthread.h>
  15. #define THREAD_STACK_SIZE 1024
  16. #define THREAD_PRIORITY 20
  17. #define THREAD_TIMESLICE 10
  18. /* 针对每个线程的计数器 */
  19. volatile rt_uint32_t count[2];
  20. /* 线程1、2共用一个入口,但入口参数不同 */
  21. static void thread_entry(void *parameter)
  22. {
  23. rt_uint32_t value;
  24. value = (rt_uint32_t)parameter;
  25. while (1)
  26. {
  27. rt_kprintf("thread %d is running\n", value);
  28. rt_thread_mdelay(1000); //延时一段时间
  29. }
  30. }
  31. static rt_thread_t tid1 = RT_NULL;
  32. static rt_thread_t tid2 = RT_NULL;
  33. static void hook_of_scheduler(struct rt_thread *from, struct rt_thread *to)
  34. {
  35. rt_kprintf("from: %s --> to: %s \n", from->name, to->name);
  36. }
  37. int scheduler_hook(void)
  38. {
  39. /* 设置调度器钩子 */
  40. rt_scheduler_sethook(hook_of_scheduler);
  41. /* 创建线程1 */
  42. tid1 = rt_thread_create("thread1",
  43. thread_entry, (void *)1,
  44. THREAD_STACK_SIZE,
  45. THREAD_PRIORITY, THREAD_TIMESLICE);
  46. if (tid1 != RT_NULL)
  47. rt_thread_startup(tid1);
  48. /* 创建线程2 */
  49. tid2 = rt_thread_create("thread2",
  50. thread_entry, (void *)2,
  51. THREAD_STACK_SIZE,
  52. THREAD_PRIORITY, THREAD_TIMESLICE - 5);
  53. if (tid2 != RT_NULL)
  54. rt_thread_startup(tid2);
  55. return 0;
  56. }
  57. /* 导出到 msh 命令列表中 */
  58. MSH_CMD_EXPORT(scheduler_hook, scheduler_hook sample);