Sharvil Nanavati | c11b407 | 2014-05-02 23:55:09 -0700 | [diff] [blame] | 1 | #define LOG_TAG "osi_semaphore" |
| 2 | |
| 3 | #include <assert.h> |
| 4 | #include <errno.h> |
| 5 | #include <string.h> |
| 6 | #include <sys/eventfd.h> |
| 7 | #include <utils/Log.h> |
| 8 | |
| 9 | #include "semaphore.h" |
| 10 | |
| 11 | #if !defined(EFD_SEMAPHORE) |
| 12 | # define EFD_SEMAPHORE (1 << 0) |
| 13 | #endif |
| 14 | |
| 15 | struct semaphore_t { |
| 16 | int fd; |
| 17 | }; |
| 18 | |
| 19 | semaphore_t *semaphore_new(unsigned int value) { |
| 20 | semaphore_t *ret = malloc(sizeof(semaphore_t)); |
| 21 | if (ret) { |
| 22 | ret->fd = eventfd(value, EFD_SEMAPHORE); |
| 23 | if (ret->fd == -1) { |
| 24 | ALOGE("%s unable to allocate semaphore: %s", __func__, strerror(errno)); |
| 25 | free(ret); |
| 26 | ret = NULL; |
| 27 | } |
| 28 | } |
| 29 | return ret; |
| 30 | } |
| 31 | |
| 32 | void semaphore_free(semaphore_t *semaphore) { |
| 33 | if (semaphore->fd != -1) |
| 34 | close(semaphore->fd); |
| 35 | free(semaphore); |
| 36 | } |
| 37 | |
| 38 | void semaphore_wait(semaphore_t *semaphore) { |
| 39 | assert(semaphore != NULL); |
| 40 | assert(semaphore->fd != -1); |
| 41 | |
| 42 | uint64_t value; |
| 43 | if (eventfd_read(semaphore->fd, &value) == -1) |
| 44 | ALOGE("%s unable to wait on semaphore: %s", __func__, strerror(errno)); |
| 45 | } |
| 46 | |
| 47 | void semaphore_post(semaphore_t *semaphore) { |
| 48 | assert(semaphore != NULL); |
| 49 | assert(semaphore->fd != -1); |
| 50 | |
| 51 | if (eventfd_write(semaphore->fd, 1ULL) == -1) |
| 52 | ALOGE("%s unable to post to semaphore: %s", __func__, strerror(errno)); |
| 53 | } |