This is an automated email from the ASF dual-hosted git repository. xiaoxiang781216 pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/nuttx.git
commit ef20f417f0610a1554109b70762bc2c1a53d5ce2 Author: pangzhen1 <[email protected]> AuthorDate: Fri Oct 23 22:06:36 2026 +0800 libc/pthread: Make cond wait release and block atomic. pthread_cond_wait() and pthread_cond_clockwait() release the mutex and only then block on cond->sem. If the waiter is preempted in between, another thread can take the mutex, call pthread_cond_signal() (the post finds no blocked waiter and just raises the count) and then wait on the same condition itself, consuming that post. The original waiter blocks afterwards and both threads wait forever. PSE52 pthread_cancel, pthread_sigmask and sigwait stress hang this way with RR scheduling: the coredumps show flag == 1, wait_count == 2 and semcount == -2 with both threads on the cond waitlist and the mutex free. Hold sched_lock() across the release and the block so no other thread on this CPU can run in the window. Blocking with the scheduler locked is already done by nxsem_wait_slow() for priority inheritance. This does not close the window against threads on another CPU under SMP. Assisted-by: Kiro:auto Signed-off-by: pangzhen1 <[email protected]> --- libs/libc/pthread/pthread_condclockwait.c | 5 +++++ libs/libc/pthread/pthread_condwait.c | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/libs/libc/pthread/pthread_condclockwait.c b/libs/libc/pthread/pthread_condclockwait.c index f49ed6659b8..23687307b74 100644 --- a/libs/libc/pthread/pthread_condclockwait.c +++ b/libs/libc/pthread/pthread_condclockwait.c @@ -43,6 +43,7 @@ #include <nuttx/cancelpt.h> #include <nuttx/pthread.h> #include <nuttx/atomic.h> +#include <nuttx/sched.h> #include "pthread.h" @@ -124,6 +125,8 @@ int pthread_cond_clockwait(FAR pthread_cond_t *cond, sinfo("Give up mutex...\n"); + sched_lock(); + atomic_add(COND_WAIT_COUNT(cond), 1); /* Give up the mutex */ @@ -139,6 +142,8 @@ int pthread_cond_clockwait(FAR pthread_cond_t *cond, } } + sched_unlock(); + /* Reacquire the mutex (retaining the ret). */ sinfo("Re-locking...\n"); diff --git a/libs/libc/pthread/pthread_condwait.c b/libs/libc/pthread/pthread_condwait.c index 638eb6a8727..be6326c92a3 100644 --- a/libs/libc/pthread/pthread_condwait.c +++ b/libs/libc/pthread/pthread_condwait.c @@ -35,6 +35,7 @@ #include <nuttx/atomic.h> #include <nuttx/cancelpt.h> #include <nuttx/pthread.h> +#include <nuttx/sched.h> #include "pthread.h" @@ -90,10 +91,16 @@ int pthread_cond_wait(FAR pthread_cond_t *cond, FAR pthread_mutex_t *mutex) sinfo("Give up mutex / take cond\n"); + /* Unlock and block atomically, or a later waiter can steal the post */ + + sched_lock(); + atomic_add(COND_WAIT_COUNT(cond), 1); ret = pthread_mutex_breaklock(mutex, &nlocks); status = -nxsem_wait_uninterruptible(&cond->sem); + sched_unlock(); + if (ret == OK) { /* Report the first failure that occurs */
