mutex.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /******************************************************************************
  2. *
  3. * Copyright (C) 2015 Google, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at:
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. ******************************************************************************/
  18. #include "osi/mutex.h"
  19. /* static section */
  20. static osi_mutex_t gl_mutex; /* Recursive Type */
  21. /** Create a new mutex
  22. * @param mutex pointer to the mutex to create
  23. * @return a new mutex */
  24. int osi_mutex_new(osi_mutex_t *mutex)
  25. {
  26. int xReturn = -1;
  27. *mutex = xSemaphoreCreateMutex();
  28. if (*mutex != NULL) {
  29. xReturn = 0;
  30. }
  31. return xReturn;
  32. }
  33. /** Lock a mutex
  34. * @param mutex the mutex to lock */
  35. int osi_mutex_lock(osi_mutex_t *mutex, uint32_t timeout)
  36. {
  37. int ret = 0;
  38. if (timeout == OSI_MUTEX_MAX_TIMEOUT) {
  39. if (xSemaphoreTake(*mutex, portMAX_DELAY) != pdTRUE) {
  40. ret = -1;
  41. }
  42. } else {
  43. if (xSemaphoreTake(*mutex, timeout / portTICK_PERIOD_MS) != pdTRUE) {
  44. ret = -2;
  45. }
  46. }
  47. return ret;
  48. }
  49. /** Unlock a mutex
  50. * @param mutex the mutex to unlock */
  51. void osi_mutex_unlock(osi_mutex_t *mutex)
  52. {
  53. xSemaphoreGive(*mutex);
  54. }
  55. /** Delete a semaphore
  56. * @param mutex the mutex to delete */
  57. void osi_mutex_free(osi_mutex_t *mutex)
  58. {
  59. vSemaphoreDelete(*mutex);
  60. *mutex = NULL;
  61. }
  62. int osi_mutex_global_init(void)
  63. {
  64. gl_mutex = xSemaphoreCreateRecursiveMutex();
  65. if (gl_mutex == NULL) {
  66. return -1;
  67. }
  68. return 0;
  69. }
  70. void osi_mutex_global_deinit(void)
  71. {
  72. vSemaphoreDelete(gl_mutex);
  73. }
  74. void osi_mutex_global_lock(void)
  75. {
  76. xSemaphoreTakeRecursive(gl_mutex, portMAX_DELAY);
  77. }
  78. void osi_mutex_global_unlock(void)
  79. {
  80. xSemaphoreGiveRecursive(gl_mutex);
  81. }