Skip to content

Commit 1831431

Browse files
committed
lib: posix: semaphore: use consistent timebase in sem_timedwait
In the Zephyr implementation, `sem_timedwait()` uses a potentially wildly different timebase for comparison via `k_uptime_get()` (uptime in ms). The standard specifies `CLOCK_REALTIME`. However, the real-time clock can be modified to an arbitrary value via clock_settime() and there is no guarantee that it will always reflect uptime. This change ensures that `sem_timedwait()` uses a more consistent timebase for comparison. Fixes #46807 Signed-off-by: Christopher Friedt <[email protected]> (cherry picked from commit 9d433c8)
1 parent 765f63c commit 1831431

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

lib/posix/Kconfig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ config POSIX_API
1919
config PTHREAD_IPC
2020
bool "POSIX pthread IPC API"
2121
default y if POSIX_API
22+
depends on POSIX_CLOCK
2223
help
2324
This enables a mostly-standards-compliant implementation of
2425
the pthread mutex, condition variable and barrier IPC

lib/posix/semaphore.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ int sem_post(sem_t *semaphore)
9191
int sem_timedwait(sem_t *semaphore, struct timespec *abstime)
9292
{
9393
int32_t timeout;
94+
struct timespec current;
9495
int64_t current_ms, abstime_ms;
9596

9697
__ASSERT(abstime, "abstime pointer NULL");
@@ -100,8 +101,12 @@ int sem_timedwait(sem_t *semaphore, struct timespec *abstime)
100101
return -1;
101102
}
102103

103-
current_ms = (int64_t)k_uptime_get();
104+
if (clock_gettime(CLOCK_REALTIME, &current) < 0) {
105+
return -1;
106+
}
107+
104108
abstime_ms = (int64_t)_ts_to_ms(abstime);
109+
current_ms = (int64_t)_ts_to_ms(&current);
105110

106111
if (abstime_ms <= current_ms) {
107112
timeout = 0;

samples/net/sockets/socketpair/prj.conf

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ CONFIG_TEST_RANDOM_GENERATOR=y
1212

1313
# Use Portable threads
1414
CONFIG_PTHREAD_IPC=y
15+
CONFIG_POSIX_CLOCK=y
1516
CONFIG_NET_SOCKETS_POSIX_NAMES=y

0 commit comments

Comments
 (0)