idlehook_sample.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. * 2020-10-17 Meco Man translate to English comment
  10. */
  11. /*
  12. * Demo: idle hook
  13. *
  14. * This demo creates a thread and set an idle thread hook function. The idle
  15. * thread hook function will be invoked when thread #1 is delaying.
  16. *
  17. * read more:
  18. * https://www.rt-thread.io/document/site/programming-manual/thread/thread/#set-and-delete-idle-hooks
  19. * https://www.rt-thread.io/document/site/programming-manual/thread/thread/#idle-thread
  20. */
  21. #include <rtthread.h>
  22. #define THREAD_PRIORITY 20
  23. #define THREAD_STACK_SIZE 1024
  24. #define THREAD_TIMESLICE 5
  25. /* thread handler */
  26. static rt_thread_t tid = RT_NULL;
  27. /* idle thread hook function running number of times */
  28. volatile static int hook_times = 0;
  29. /* idle thread hook function */
  30. static void idle_hook()
  31. {
  32. if (0 == (hook_times % 10000))
  33. {
  34. rt_kprintf("enter idle hook %d times.\n", hook_times);
  35. }
  36. rt_enter_critical();
  37. hook_times++;
  38. rt_exit_critical();
  39. }
  40. /* thread entry function */
  41. static void thread_entry(void *parameter)
  42. {
  43. int i = 5;
  44. while (i--)
  45. {
  46. rt_kprintf("enter thread1.\n");
  47. rt_enter_critical();
  48. hook_times = 0;
  49. rt_exit_critical();
  50. /* sleep for 500ms */
  51. rt_kprintf("thread1 delay 500ms.\n");
  52. rt_thread_mdelay(500);
  53. }
  54. rt_kprintf("delete idle hook.\n");
  55. /* remove idle thread hook function */
  56. rt_thread_idle_delhook(idle_hook);
  57. rt_kprintf("thread1 finish.\n");
  58. }
  59. int idle_hook_sample(void)
  60. {
  61. /* set idle thread hook function */
  62. rt_thread_idle_sethook(idle_hook);
  63. /* create thread #1 */
  64. tid = rt_thread_create("thread1",
  65. thread_entry, RT_NULL,
  66. THREAD_STACK_SIZE,
  67. THREAD_PRIORITY, THREAD_TIMESLICE);
  68. if (tid != RT_NULL)
  69. rt_thread_startup(tid);
  70. return 0;
  71. }
  72. /* export the msh command */
  73. MSH_CMD_EXPORT(idle_hook_sample, idle hook sample);