From 8d0d51960e98e46c8c286a1a32b8edd6f96c0c63 Mon Sep 17 00:00:00 2001 From: Matthias Kruk Date: Sat, 17 Apr 2021 09:28:00 +0900 Subject: [PATCH] include/sem: Work around busy-waiting in sem_wait() The sem_wait() function is implemented using busy-waiting, which is not good for the environment. This commit adds a call to inotifywait as a temporary workaround to avoid the busy-waiting. --- include/sem.sh | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/include/sem.sh b/include/sem.sh index b59ac13..224e771 100644 --- a/include/sem.sh +++ b/include/sem.sh @@ -173,16 +173,26 @@ sem_wait() { mutex=$(_sem_mutexpath "$name") sem=$(_sem_sempath "$name") - passed=0 + passed=false - while (( passed == 0 )); do + while ! "$passed"; do mutex_lock "$mutex" if _sem_dec "$sem"; then - passed=1 + passed=true fi mutex_unlock "$mutex" + + # Workaround to prevent busy-waiting. The semaphore + # might get increased before we get to the inotifywait, + # in which case we'd wait for a whole second, during + # which another process might pass the semaphore. This + # is not ideal, but to prevent this we'd need something + # like pthread_cond_wait(). + if ! "$passed"; then + inotifywait -qq -t 1 "$sem" + fi done return 0 -- 2.47.3