semaphore: add a new semaphore_timedwait helper

This is the same as semaphore_wait except it allows for the acquire
attempt to time out after a given period of time.
This commit is contained in:
8infy
2024-09-01 19:39:25 +03:00
parent 0854d08020
commit 7e3922c7ad
2 changed files with 19 additions and 0 deletions
+2
View File
@@ -4,6 +4,7 @@
#include <stddef.h>
#include <stdbool.h>
#include <spinlock.h>
#include <time.h>
#define SEM_TAIL 0
#define SEM_HEAD 1
@@ -24,6 +25,7 @@ typedef struct semaphore_t{
int semaphore_wait(semaphore_t *sem, bool interruptible);
int semaphore_timedwait(semaphore_t *sem, time_t timeoutusec, bool interruptible);
void semaphore_signal(semaphore_t *sem);
bool semaphore_test(semaphore_t *sem);
bool semaphore_haswaiters(semaphore_t *sem);
+17
View File
@@ -88,6 +88,23 @@ int semaphore_wait(semaphore_t *sem, bool interruptible) {
return ret;
}
int semaphore_timedwait(semaphore_t *sem, time_t timeoutusec, bool interruptible) {
time_t sleepus;
do {
if (semaphore_test(sem))
return true;
sleepus = min(timeoutusec, 10);
timeoutusec -= sleepus;
if (sleepus)
sched_sleepus(sleepus);
} while (timeoutusec);
return false;
}
void semaphore_signal(semaphore_t *sem) {
bool intstate = interrupt_set(false);
spinlock_acquire(&sem->lock);