Skip to content

Commit

Permalink
semaphore: add sem_value() helper function
Browse files Browse the repository at this point in the history
This function returns current value of the semaphore.

Signed-off-by: Pawel Wieczorkiewicz <[email protected]>
  • Loading branch information
wipawel authored and bjoernd committed Aug 6, 2021
1 parent 633a57f commit ced3149
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
2 changes: 2 additions & 0 deletions include/semaphore.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ typedef struct sem sem_t;
.v = {(value) } \
}

extern int32_t sem_value(const sem_t *sem);

extern void sem_init(sem_t *sem, uint32_t value);
extern bool sem_trywait(sem_t *sem);
extern void sem_wait(sem_t *sem);
Expand Down
4 changes: 3 additions & 1 deletion lib/semaphore.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ void sem_init(sem_t *sem, uint32_t value) {
atomic_set(&(sem->v), value);
}

int32_t sem_value(const sem_t *sem) { return atomic_read(&sem->v); }

bool sem_trywait(sem_t *sem) {
int64_t val;

if (atomic_read(&(sem->v)) > 0) {
if (sem_value(sem) > 0) {
val = atomic_dec_return(&(sem->v));
if (val >= 0) {
return true;
Expand Down

0 comments on commit ced3149

Please sign in to comment.