]> git.corax.cc Git - toolbox/commitdiff
include/sem: Work around busy-waiting in sem_wait()
authorMatthias Kruk <m@m10k.eu>
Sat, 17 Apr 2021 00:28:00 +0000 (09:28 +0900)
committerMatthias Kruk <m@m10k.eu>
Sat, 17 Apr 2021 00:28:00 +0000 (09:28 +0900)
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

index b59ac13d47b3769f5315fa317bc22e18f52b8adb..224e7713b4da89c8e1c94932e39f35266f79137e 100644 (file)
@@ -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