scheduler_hook.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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: scheduler hook
  13. *
  14. * This demo sets a scheduler hook function and prints context-switching information.
  15. *
  16. * read more:
  17. * https://www.rt-thread.io/document/site/thread/thread/#set-the-scheduler-hook
  18. */
  19. #include <rtthread.h>
  20. #define THREAD_STACK_SIZE 1024
  21. #define THREAD_PRIORITY 20
  22. #define THREAD_TIMESLICE 10
  23. /* counter for each thread */
  24. volatile rt_uint32_t count[2];
  25. /* thread entry function */
  26. /* threads #1 and #2 share one entry, but the entry parameter is different */
  27. static void thread_entry(void *parameter)
  28. {
  29. rt_uint32_t value;
  30. value = (rt_uint32_t)parameter;
  31. while (1)
  32. {
  33. rt_kprintf("thread %d is running\n", value);
  34. rt_thread_mdelay(1000);
  35. }
  36. }
  37. /* thread(s) handler */
  38. static rt_thread_t tid1 = RT_NULL;
  39. static rt_thread_t tid2 = RT_NULL;
  40. static void hook_of_scheduler(struct rt_thread *from, struct rt_thread *to)
  41. {
  42. rt_kprintf("from: %s --> to: %s \n", from->name, to->name);
  43. }
  44. int scheduler_hook(void)
  45. {
  46. /* set a scheduler hook function */
  47. rt_scheduler_sethook(hook_of_scheduler);
  48. tid1 = rt_thread_create("thread1",
  49. thread_entry, (void *)1,
  50. THREAD_STACK_SIZE,
  51. THREAD_PRIORITY, THREAD_TIMESLICE);
  52. if (tid1 != RT_NULL)
  53. rt_thread_startup(tid1);
  54. tid2 = rt_thread_create("thread2",
  55. thread_entry, (void *)2,
  56. THREAD_STACK_SIZE,
  57. THREAD_PRIORITY, THREAD_TIMESLICE - 5);
  58. if (tid2 != RT_NULL)
  59. rt_thread_startup(tid2);
  60. return 0;
  61. }
  62. /* export the msh command */
  63. MSH_CMD_EXPORT(scheduler_hook, scheduler_hook sample);