scheduler_hook.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. #if RT_VER_NUM >= 0x50001
  36. rt_kprintf("from: %s --> to: %s \n", from->parent.name, to->parent.name);
  37. #else
  38. rt_kprintf("from: %s --> to: %s \n", from->name, to->name);
  39. #endif
  40. }
  41. int scheduler_hook(void)
  42. {
  43. /* 设置调度器钩子 */
  44. rt_scheduler_sethook(hook_of_scheduler);
  45. /* 创建线程1 */
  46. tid1 = rt_thread_create("thread1",
  47. thread_entry, (void *)1,
  48. THREAD_STACK_SIZE,
  49. THREAD_PRIORITY, THREAD_TIMESLICE);
  50. if (tid1 != RT_NULL)
  51. rt_thread_startup(tid1);
  52. /* 创建线程2 */
  53. tid2 = rt_thread_create("thread2",
  54. thread_entry, (void *)2,
  55. THREAD_STACK_SIZE,
  56. THREAD_PRIORITY, THREAD_TIMESLICE - 5);
  57. if (tid2 != RT_NULL)
  58. rt_thread_startup(tid2);
  59. return 0;
  60. }
  61. /* 导出到 msh 命令列表中 */
  62. MSH_CMD_EXPORT(scheduler_hook, scheduler_hook sample);