Skip to content

Commit 2b77caa

Browse files
committed
Add Semaphore::wait_until
Given the 64-bit timebase, add wait_until to Semaphore. Naming is based on Thread::wait_until. pthreads uses "timedwait", but that's not a good fit against our existing wait() - pthreads only has an absolute-time wait, not relative.
1 parent cd573a6 commit 2b77caa

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

rtos/Semaphore.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
* SOFTWARE.
2121
*/
2222
#include "rtos/Semaphore.h"
23+
#include "rtos/Kernel.h"
2324
#include "platform/mbed_assert.h"
2425

2526
#include <string.h>
@@ -57,6 +58,20 @@ int32_t Semaphore::wait(uint32_t millisec) {
5758
}
5859
}
5960

61+
int32_t Semaphore::wait_until(uint64_t millisec) {
62+
uint64_t now = Kernel::get_ms_count();
63+
uint32_t timeout;
64+
65+
if (now >= millisec) {
66+
return wait(0);
67+
} else if (millisec - now >= osWaitForever) {
68+
// API permits early return
69+
return wait(osWaitForever - 1);
70+
} else {
71+
return wait(millisec - now);
72+
}
73+
}
74+
6075
osStatus Semaphore::release(void) {
6176
return osSemaphoreRelease(_id);
6277
}

rtos/Semaphore.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,18 @@ class Semaphore : private mbed::NonCopyable<Semaphore> {
6767
*/
6868
int32_t wait(uint32_t millisec=osWaitForever);
6969

70+
/** Wait until a Semaphore resource becomes available.
71+
@param millisec absolute timeout time, referenced to Kernel::get_ms_count()
72+
@return number of available tokens, before taking one; or -1 in case of incorrect parameters
73+
@note the underlying RTOS may have a limit to the maximum wait time
74+
due to internal 32-bit computations, but this is guaranteed to work if the
75+
wait is <= 0x7fffffff milliseconds (~24 days). If the limit is exceeded,
76+
the acquire attempt will time out earlier than specified.
77+
78+
@note You cannot call this function from ISR context.
79+
*/
80+
int32_t wait_until(uint64_t millisec);
81+
7082
/** Release a Semaphore resource that was obtain with Semaphore::wait.
7183
@return status code that indicates the execution status of the function:
7284
@a osOK the token has been correctly released.

0 commit comments

Comments
 (0)