semaphore_static.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <rtthread.h>
  2. #include "tc_comm.h"
  3. static struct rt_semaphore sem;
  4. struct rt_thread thread;
  5. static char thread_stack[THREAD_STACK_SIZE];
  6. static void thread_entry(void* parameter)
  7. {
  8. rt_err_t result;
  9. rt_tick_t tick;
  10. /* get current tick */
  11. tick = rt_tick_get();
  12. /* take a semaphore for 10 OS Tick */
  13. result = rt_sem_take(&sem, 10);
  14. if (result == -RT_ETIMEOUT)
  15. {
  16. if (rt_tick_get() - tick != 10)
  17. {
  18. tc_done(TC_STAT_FAILED);
  19. rt_sem_detach(&sem);
  20. return;
  21. }
  22. rt_kprintf("take semaphore timeout");
  23. }
  24. else
  25. {
  26. tc_done(TC_STAT_FAILED);
  27. rt_sem_detach(&sem);
  28. return;
  29. }
  30. /* release semaphore one time */
  31. rt_sem_release(&sem);
  32. result = rt_sem_take(&sem, RT_WAITING_FOREVER);
  33. if (result != RT_EOK)
  34. {
  35. tc_done(TC_STAT_FAILED);
  36. rt_sem_detach(&sem);
  37. return;
  38. }
  39. /* testcase passed */
  40. tc_done(TC_STAT_PASSED);
  41. /* detach semaphore */
  42. rt_sem_detach(&sem);
  43. }
  44. int semaphore_static_init()
  45. {
  46. rt_err_t result;
  47. result = rt_sem_init(&sem, "sem", 0, RT_IPC_FLAG_FIFO);
  48. if (result != RT_EOK)
  49. {
  50. tc_stat(TC_STAT_END | TC_STAT_FAILED);
  51. return 0;
  52. }
  53. result = rt_thread_init(&thread, "test",
  54. thread_entry, RT_NULL,
  55. thread_stack, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
  56. if (result == RT_EOK)
  57. rt_thread_startup(&thread);
  58. else
  59. tc_stat(TC_STAT_END | TC_STAT_FAILED);
  60. return 0;
  61. }
  62. #ifdef RT_USING_TC
  63. static void _tc_cleanup()
  64. {
  65. /* lock scheduler */
  66. rt_enter_critical();
  67. if (thread.stat != RT_THREAD_CLOSE)
  68. rt_thread_detach(&thread);
  69. /* unlock scheduler */
  70. rt_exit_critical();
  71. }
  72. int _tc_semaphore_static()
  73. {
  74. /* set tc cleanup */
  75. tc_cleanup(_tc_cleanup);
  76. semaphore_static_init();
  77. return 30;
  78. }
  79. FINSH_FUNCTION_EXPORT(_tc_semaphore_static, a static semaphore test);
  80. #else
  81. int rt_application_init()
  82. {
  83. semaphore_static_init();
  84. return 0;
  85. }
  86. #endif