From: Matthias Kruk Date: Sat, 17 Apr 2021 00:28:00 +0000 (+0900) Subject: include/sem: Work around busy-waiting in sem_wait() X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=8d0d51960e98e46c8c286a1a32b8edd6f96c0c63;p=toolbox 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. --- 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