thread_yield.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. *
  8. */
  9. #include <rtthread.h>
  10. #include "tc_comm.h"
  11. /* 指向线程控制块的指针 */
  12. static rt_thread_t tid1 = RT_NULL;
  13. static rt_thread_t tid2 = RT_NULL;
  14. /* 线程1入口 */
  15. static void thread1_entry(void* parameter)
  16. {
  17. rt_uint32_t count = 0;
  18. while (1)
  19. {
  20. /* 打印线程1的输出 */
  21. rt_kprintf("thread1: count = %d\n", count ++);
  22. /* 执行yield后应该切换到thread2执行 */
  23. rt_thread_yield();
  24. }
  25. }
  26. /* 线程2入口 */
  27. static void thread2_entry(void* parameter)
  28. {
  29. rt_uint32_t count = 0;
  30. while (1)
  31. {
  32. /* 打印线程2的输出 */
  33. rt_kprintf("thread2: count = %d\n", count ++);
  34. /* 执行yield后应该切换到thread1执行 */
  35. rt_thread_yield();
  36. }
  37. }
  38. int thread_yield_init()
  39. {
  40. /* 创建线程1 */
  41. tid1 = rt_thread_create("thread",
  42. thread1_entry, RT_NULL, /* 线程入口是thread1_entry, 入口参数是RT_NULL */
  43. THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
  44. if (tid1 != RT_NULL)
  45. rt_thread_startup(tid1);
  46. else
  47. tc_stat(TC_STAT_END | TC_STAT_FAILED);
  48. /* 创建线程2 */
  49. tid2 = rt_thread_create("thread",
  50. thread2_entry, RT_NULL, /* 线程入口是thread2_entry, 入口参数是RT_NULL */
  51. THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
  52. if (tid2 != RT_NULL)
  53. rt_thread_startup(tid2);
  54. else
  55. tc_stat(TC_STAT_END | TC_STAT_FAILED);
  56. return 0;
  57. }
  58. #ifdef RT_USING_TC
  59. static void _tc_cleanup()
  60. {
  61. /* 调度器上锁,上锁后,将不再切换到其他线程,仅响应中断 */
  62. rt_enter_critical();
  63. /* 删除线程 */
  64. if (tid1 != RT_NULL && tid1->stat != RT_THREAD_CLOSE)
  65. rt_thread_delete(tid1);
  66. if (tid2 != RT_NULL && tid2->stat != RT_THREAD_CLOSE)
  67. rt_thread_delete(tid2);
  68. /* 调度器解锁 */
  69. rt_exit_critical();
  70. /* 设置TestCase状态 */
  71. tc_done(TC_STAT_PASSED);
  72. }
  73. int _tc_thread_yield()
  74. {
  75. /* 设置TestCase清理回调函数 */
  76. tc_cleanup(_tc_cleanup);
  77. thread_yield_init();
  78. /* 返回TestCase运行的最长时间 */
  79. return 30;
  80. }
  81. /* 输出函数命令到finsh shell中 */
  82. FINSH_FUNCTION_EXPORT(_tc_thread_yield, a thread yield example);
  83. #else
  84. /* 用户应用入口 */
  85. int rt_application_init()
  86. {
  87. thread_yield_init();
  88. return 0;
  89. }
  90. #endif