idlehook_sample.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2006-2018, 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. */
  15. #include <rtthread.h>
  16. #include <rthw.h>
  17. #define THREAD_PRIORITY 20
  18. #define THREAD_STACK_SIZE 1024
  19. #define THREAD_TIMESLICE 5
  20. /* 指向线程控制块的指针 */
  21. static rt_thread_t tid = RT_NULL;
  22. /* 空闲函数钩子函数执行次数 */
  23. volatile static int hook_times = 0;
  24. /* 空闲任务钩子函数 */
  25. static void idle_hook()
  26. {
  27. if (0 == (hook_times % 10000))
  28. {
  29. rt_kprintf("enter idle hook %d times.\n", hook_times);
  30. }
  31. rt_enter_critical();
  32. hook_times++;
  33. rt_exit_critical();
  34. }
  35. /* 线程入口 */
  36. static void thread_entry(void *parameter)
  37. {
  38. int i = 5;
  39. while (i--)
  40. {
  41. rt_kprintf("enter thread1.\n");
  42. rt_enter_critical();
  43. hook_times = 0;
  44. rt_exit_critical();
  45. /* 休眠500ms */
  46. rt_kprintf("thread1 delay 50 OS Tick.\n", hook_times);
  47. rt_thread_mdelay(500);
  48. }
  49. rt_kprintf("delete idle hook.\n");
  50. /* 删除空闲钩子函数 */
  51. rt_thread_idle_delhook(idle_hook);
  52. rt_kprintf("thread1 finish.\n");
  53. }
  54. int idle_hook_sample(void)
  55. {
  56. /* 设置空闲线程钩子 */
  57. rt_thread_idle_sethook(idle_hook);
  58. /* 创建线程 */
  59. tid = rt_thread_create("thread1",
  60. thread_entry, RT_NULL,
  61. THREAD_STACK_SIZE,
  62. THREAD_PRIORITY, THREAD_TIMESLICE);
  63. if (tid != RT_NULL)
  64. rt_thread_startup(tid);
  65. return 0;
  66. }
  67. /* 导出到 msh 命令列表中 */
  68. MSH_CMD_EXPORT(idle_hook_sample, idle hook sample);