test_semaphore_binary_static.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. */
  10. /*
  11. * Demo: semaphore
  12. * This demo creates one binary semaphore statically
  13. * It creates two tasks:
  14. * 1) task #1: give the semaphore
  15. * 2) task #2: take the semaphore
  16. *
  17. */
  18. #include <FreeRTOS.h>
  19. #include <semphr.h>
  20. #include <task.h>
  21. #define TASK_PRIORITY 25
  22. /* Semaphore handle */
  23. static SemaphoreHandle_t static_sem = NULL;
  24. /* Buffer to store semaphore structure */
  25. static StaticSemaphore_t xMutexBuffer;
  26. static TaskHandle_t TaskHandle1 = NULL;
  27. static TaskHandle_t TaskHandle2 = NULL;
  28. static void vTask1Code(void *pvParameters)
  29. {
  30. static BaseType_t result;
  31. static BaseType_t count = 0;
  32. while (1)
  33. {
  34. if (count <= 100)
  35. {
  36. count++;
  37. }
  38. else
  39. return;
  40. /* Release the semaphore when count is incremented by 10 */
  41. if (0 == (count % 10))
  42. {
  43. rt_kprintf("task1 release a static semaphore.\n");
  44. result = xSemaphoreGive(static_sem);
  45. if (result != pdPASS)
  46. {
  47. rt_kprintf("task1 release a static semaphore, failed.\n");
  48. return;
  49. }
  50. }
  51. }
  52. }
  53. static void vTask2Code(void * pvParameters)
  54. {
  55. static BaseType_t result;
  56. static BaseType_t number = 0;
  57. while (1)
  58. {
  59. /* Block on the semaphore indefinitely. Increment number after taking the semaphore */
  60. result = xSemaphoreTake(static_sem, portMAX_DELAY);
  61. if (result != pdPASS)
  62. {
  63. rt_kprintf("task2 take a static semaphore, failed.\n");
  64. return;
  65. }
  66. else
  67. {
  68. number++;
  69. rt_kprintf("task2 take a static semaphore. number = %d\n", number);
  70. }
  71. }
  72. }
  73. int semaphore_binary_static()
  74. {
  75. /* Create a binary semaphore statically */
  76. static_sem = xSemaphoreCreateBinaryStatic(&xMutexBuffer);
  77. if (static_sem == NULL)
  78. {
  79. rt_kprintf("create static semaphore failed.\n");
  80. return -1;
  81. }
  82. xTaskCreate( vTask1Code, "Task1", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY, &TaskHandle1 );
  83. if (TaskHandle1 == NULL)
  84. {
  85. rt_kprintf("Create task 1 failed\n");
  86. return -1;
  87. }
  88. xTaskCreate( vTask2Code, "Task2", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY + 1, &TaskHandle2 );
  89. if (TaskHandle2 == NULL)
  90. {
  91. rt_kprintf("Create task 2 failed\n");
  92. return -1;
  93. }
  94. return 0;
  95. }
  96. MSH_CMD_EXPORT(semaphore_binary_static, semaphore sample);