test_semaphore_binary_dynamic.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 dynamically
  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 (FINSH_THREAD_PRIORITY + 1)
  22. /* Semaphore handle */
  23. static SemaphoreHandle_t dynamic_sem = NULL;
  24. static TaskHandle_t TaskHandle1 = NULL;
  25. static TaskHandle_t TaskHandle2 = NULL;
  26. static void vTask1Code(void *pvParameters)
  27. {
  28. static BaseType_t result;
  29. static BaseType_t count = 0;
  30. while (1)
  31. {
  32. if (count <= 100)
  33. {
  34. count++;
  35. }
  36. else
  37. return;
  38. /* Release the semaphore when count is incremented by 10 */
  39. if (0 == (count % 10))
  40. {
  41. rt_kprintf("task1 release a dynamic semaphore.\n");
  42. result = xSemaphoreGive(dynamic_sem);
  43. if (result != pdPASS)
  44. {
  45. rt_kprintf("task1 release a dynamic semaphore, failed.\n");
  46. return;
  47. }
  48. }
  49. }
  50. }
  51. static void vTask2Code(void * pvParameters)
  52. {
  53. static BaseType_t result;
  54. static BaseType_t number = 0;
  55. while (1)
  56. {
  57. /* Block on the semaphore indefinitely. Increment number after taking the semaphore */
  58. result = xSemaphoreTake(dynamic_sem, portMAX_DELAY);
  59. if (result != pdPASS)
  60. {
  61. rt_kprintf("task2 take a dynamic semaphore, failed.\n");
  62. return;
  63. }
  64. else
  65. {
  66. number++;
  67. rt_kprintf("task2 take a dynamic semaphore. number = %d\n", number);
  68. }
  69. }
  70. }
  71. int semaphore_binary_dynamic()
  72. {
  73. /* Create a binary semaphore dynamically */
  74. dynamic_sem = xSemaphoreCreateBinary();
  75. if (dynamic_sem == NULL)
  76. {
  77. rt_kprintf("create dynamic semaphore failed.\n");
  78. return -1;
  79. }
  80. xTaskCreate( vTask2Code, "Task2", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY + 1, &TaskHandle2 );
  81. if (TaskHandle2 == NULL)
  82. {
  83. rt_kprintf("Create task 2 failed\n");
  84. return -1;
  85. }
  86. xTaskCreate( vTask1Code, "Task1", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY, &TaskHandle1 );
  87. if (TaskHandle1 == NULL)
  88. {
  89. rt_kprintf("Create task 1 failed\n");
  90. return -1;
  91. }
  92. return 0;
  93. }
  94. MSH_CMD_EXPORT(semaphore_binary_dynamic, semaphore sample);