From 0df7bd26eddd57d6cc9bd23237964a3d71f6f8ac Mon Sep 17 00:00:00 2001 From: Jaxson Han Date: Mon, 10 Jul 2023 22:04:05 +0800 Subject: [PATCH] lib: posix: pthread_rwlock: Fix a racy issue Multiple reader threads unlocking the read lock simultaneously might cause the program hang because it's possible that no thread is identified as the last one to active the writer thread. To fix the issue, swap the k_sem_give sequence. Signed-off-by: Jaxson Han --- lib/posix/rwlock.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/posix/rwlock.c b/lib/posix/rwlock.c index 45d4af69458..60039fb088a 100644 --- a/lib/posix/rwlock.c +++ b/lib/posix/rwlock.c @@ -200,13 +200,13 @@ int pthread_rwlock_unlock(pthread_rwlock_t *rwlock) k_sem_give(&rwlock->wr_sem); } else { /* Read unlock */ + k_sem_give(&rwlock->rd_sem); + if (k_sem_count_get(&rwlock->rd_sem) == - (CONCURRENT_READER_LIMIT - 1)) { + CONCURRENT_READER_LIMIT) { /* Last read lock, unlock writer */ k_sem_give(&rwlock->reader_active); } - - k_sem_give(&rwlock->rd_sem); } return 0; }