semaphore.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/semaphore.h"
  19. /*-----------------------------------------------------------------------------------*/
  20. // Creates and returns a new semaphore. The "init_count" argument specifies
  21. // the initial state of the semaphore, "max_count" specifies the maximum value
  22. // that can be reached.
  23. int osi_sem_new(osi_sem_t *sem, uint32_t max_count, uint32_t init_count)
  24. {
  25. int ret = -1;
  26. if (sem) {
  27. *sem = xSemaphoreCreateCounting(max_count, init_count);
  28. if ((*sem) != NULL) {
  29. ret = 0;
  30. }
  31. }
  32. return ret;
  33. }
  34. /*-----------------------------------------------------------------------------------*/
  35. // Give a semaphore
  36. void osi_sem_give(osi_sem_t *sem)
  37. {
  38. xSemaphoreGive(*sem);
  39. }
  40. /*
  41. Blocks the thread while waiting for the semaphore to be
  42. signaled. If the "timeout" argument is non-zero, the thread should
  43. only be blocked for the specified time (measured in
  44. milliseconds).
  45. */
  46. int
  47. osi_sem_take(osi_sem_t *sem, uint32_t timeout)
  48. {
  49. int ret = 0;
  50. if (timeout == OSI_SEM_MAX_TIMEOUT) {
  51. if (xSemaphoreTake(*sem, portMAX_DELAY) != pdTRUE) {
  52. ret = -1;
  53. }
  54. } else {
  55. if (xSemaphoreTake(*sem, timeout / portTICK_PERIOD_MS) != pdTRUE) {
  56. ret = -2;
  57. }
  58. }
  59. return ret;
  60. }
  61. // Deallocates a semaphore
  62. void osi_sem_free(osi_sem_t *sem)
  63. {
  64. vSemaphoreDelete(*sem);
  65. *sem = NULL;
  66. }