Branch data Line data Source code
1 : : // Copyright 2012-2025 David Robillard <d@drobilla.net> 2 : : // SPDX-License-Identifier: ISC 3 : : 4 : : #include <zix/sem.h> 5 : : 6 : : #include "../errno_status.h" 7 : : #include "../zix_config.h" 8 : : 9 : : #include <zix/attributes.h> 10 : : #include <zix/status.h> 11 : : #include <zix/warnings.h> 12 : : 13 : : #include <semaphore.h> 14 : : 15 : : #include <errno.h> 16 : : #include <stdint.h> 17 : : #include <time.h> 18 : : 19 : : // NOLINTBEGIN(bugprone-assignment-in-selection-statement,cert-exp45-c) 20 : : 21 : : ZixStatus 22 : 6 : zix_sem_init(ZixSem* sem, unsigned initial) 23 : : { 24 : 6 : return zix_errno_status_if(sem_init(&sem->sem, 0, initial)); 25 : : } 26 : : 27 : : ZixStatus 28 : 6 : zix_sem_destroy(ZixSem* sem) 29 : : { 30 : 6 : return zix_errno_status_if(sem_destroy(&sem->sem)); 31 : : } 32 : : 33 : : ZIX_REALTIME ZixStatus 34 : 1031 : zix_sem_post(ZixSem* sem) 35 : : { 36 : : ZIX_DISABLE_EFFECT_WARNINGS 37 : 1031 : return zix_errno_status_if(sem_post(&sem->sem)); 38 : : ZIX_RESTORE_WARNINGS 39 : : } 40 : : 41 : : ZixStatus 42 : 1025 : zix_sem_wait(ZixSem* sem) 43 : : { 44 : 1025 : int r = 0; 45 [ - + - - ]: 1025 : while ((r = sem_wait(&sem->sem)) && errno == EINTR) { 46 : : // Interrupted, try again 47 : : } 48 : : 49 : 1025 : return zix_errno_status_if(r); 50 : : } 51 : : 52 : : ZixStatus 53 : 6 : zix_sem_try_wait(ZixSem* sem) 54 : : { 55 : 6 : int r = 0; 56 [ + + - + ]: 6 : while ((r = sem_trywait(&sem->sem)) && errno == EINTR) { 57 : : // Interrupted, try again 58 : : } 59 : : 60 : 6 : return zix_errno_status_if(r); 61 : : } 62 : : 63 : : ZixStatus 64 : 8 : zix_sem_timed_wait(ZixSem* sem, 65 : : const uint32_t seconds, 66 : : const uint32_t nanoseconds) 67 : : { 68 : : #if !USE_CLOCK_GETTIME || !USE_SEM_TIMEDWAIT 69 : : 70 : : (void)sem; 71 : : (void)seconds; 72 : : (void)nanoseconds; 73 : : return ZIX_STATUS_NOT_SUPPORTED; 74 : : 75 : : #else 76 : : # define NS_PER_SECOND 1000000000L 77 : : 78 : 8 : struct timespec ts = {0, 0}; 79 : : 80 : 8 : int r = 0; 81 [ + - ]: 8 : if (!(r = clock_gettime(CLOCK_REALTIME, &ts))) { 82 : 8 : ts.tv_sec += (time_t)seconds; 83 : 8 : ts.tv_nsec += (long)nanoseconds; 84 [ + + ]: 8 : if (ts.tv_nsec >= NS_PER_SECOND) { 85 : 2 : ts.tv_nsec -= NS_PER_SECOND; 86 : 2 : ts.tv_sec++; 87 : : } 88 : : 89 [ + + - + ]: 8 : while ((r = sem_timedwait(&sem->sem, &ts)) && errno == EINTR) { 90 : : // Interrupted, try again 91 : : } 92 : : } 93 : : 94 : 8 : return zix_errno_status_if(r); 95 : : 96 : : # undef NS_PER_SECOND 97 : : #endif 98 : : } 99 : : 100 : : // NOLINTEND(bugprone-assignment-in-selection-statement,cert-exp45-c)