test_mutex_recursive_static.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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: recursive mutex
  13. *
  14. * This demo demonstrates statically creating a recursive mutex and using it to manage shared resources.
  15. *
  16. */
  17. #include <FreeRTOS.h>
  18. #include <semphr.h>
  19. #include <task.h>
  20. #define TASK_PRIORITY (FINSH_THREAD_PRIORITY + 1)
  21. /* mutex handler */
  22. static SemaphoreHandle_t static_mutex = NULL;
  23. /* Buffer to store mutex structure */
  24. static StaticSemaphore_t xMutexBuffer;
  25. static TaskHandle_t TaskHandle1 = NULL;
  26. static TaskHandle_t TaskHandle2 = NULL;
  27. static BaseType_t number1, number2 = 0;
  28. static void vTask1Code(void *pvParameters)
  29. {
  30. while (1)
  31. {
  32. /* pending the mutex */
  33. xSemaphoreTakeRecursive(static_mutex, portMAX_DELAY);
  34. /* protect and deal with public variables */
  35. number1++;
  36. vTaskDelay(pdMS_TO_TICKS(10));
  37. number2++;
  38. if (number1 != number2)
  39. {
  40. rt_kprintf("not protect.number1 = %d, mumber2 = %d \n", number1, number2);
  41. }
  42. else
  43. {
  44. rt_kprintf("mutex protect ,number1 = mumber2 is %d\n", number1);
  45. }
  46. /* release the mutex */
  47. xSemaphoreGiveRecursive(static_mutex);
  48. if (number1 >= 100)
  49. {
  50. vSemaphoreDelete(static_mutex);
  51. return;
  52. }
  53. }
  54. }
  55. static void vTask2Code(void * pvParameters)
  56. {
  57. while (1)
  58. {
  59. xSemaphoreTakeRecursive(static_mutex, portMAX_DELAY);
  60. number1++;
  61. number2++;
  62. xSemaphoreGiveRecursive(static_mutex);
  63. if (number1 >= 50)
  64. return;
  65. }
  66. }
  67. int mutex_recursive_static(void)
  68. {
  69. /* Create a recursive mutex statically */
  70. static_mutex = xSemaphoreCreateRecursiveMutexStatic(&xMutexBuffer);
  71. if (static_mutex == NULL)
  72. {
  73. rt_kprintf("create static mutex failed.\n");
  74. return -1;
  75. }
  76. xTaskCreate( vTask1Code, "Task1", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY, &TaskHandle1 );
  77. if (TaskHandle1 == NULL)
  78. {
  79. rt_kprintf("Create task 1 failed\n");
  80. return -1;
  81. }
  82. xTaskCreate( vTask2Code, "Task2", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY, &TaskHandle2 );
  83. if (TaskHandle2 == NULL)
  84. {
  85. rt_kprintf("Create task 2 failed\n");
  86. return -1;
  87. }
  88. return 0;
  89. }
  90. MSH_CMD_EXPORT(mutex_recursive_static, mutex sample);