From: Matthias Kruk Date: Fri, 18 Jun 2021 07:15:24 +0000 (+0900) Subject: include/{mutex,wmutex,queue,sem}: Fix timeout behavior of blocking calls X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=b94ce8914852facec4ce7df177b9eadf8aea8ec5;p=toolbox include/{mutex,wmutex,queue,sem}: Fix timeout behavior of blocking calls Because of a bug in the timeout handling, the mutex_lock(), wmutex_lock(), queue_get(), and sem_wait() functions wait forever if a positive timeout is specified. This commit changes the behavior so that the functions will wait forever if the timeout is -1 or omitted, return immediately if the timeout is zero, or otherwise wait for the specified number of seconds. --- diff --git a/include/mutex.sh b/include/mutex.sh index eb8de81..1d04ce0 100644 --- a/include/mutex.sh +++ b/include/mutex.sh @@ -34,12 +34,12 @@ mutex_lock() { local lock="$1" local -i timeout="$2" - local -i remaining - - remaining="$timeout" + if (( $# < 2 )); then + timeout=-1 + fi while ! mutex_trylock "$lock"; do - if (( timeout != 0 && --remaining < 0 )); then + if (( timeout-- == 0 )); then return 1 fi diff --git a/include/queue.sh b/include/queue.sh index c1c8b9c..fbcb8ff 100644 --- a/include/queue.sh +++ b/include/queue.sh @@ -387,6 +387,10 @@ queue_get() { local item local err + if (( $# < 2 )); then + timeout=-1 + fi + sem=$(_queue_get_sem "$queue") mutex=$(_queue_get_mutex "$queue") data=$(_queue_get_data "$queue") diff --git a/include/sem.sh b/include/sem.sh index 8446901..7189ab7 100644 --- a/include/sem.sh +++ b/include/sem.sh @@ -191,6 +191,10 @@ sem_wait() { local counter local err + if (( $# < 2 )); then + timeout=-1 + fi + waitlock=$(_sem_get_waitlock "$name") countlock=$(_sem_get_countlock "$name") counter=$(_sem_get_counter "$name") diff --git a/include/wmutex.sh b/include/wmutex.sh index 5b8593f..3ce6f2d 100644 --- a/include/wmutex.sh +++ b/include/wmutex.sh @@ -34,12 +34,12 @@ wmutex_lock() { local lock="$1" local -i timeout="$2" - local -i remaining - - remaining="$timeout" + if (( $# < 2 )); then + timeout=-1 + fi while ! wmutex_trylock "$lock"; do - if (( timeout != 0 && --remaining < 0 )); then + if (( timeout-- == 0 )); then return 1 fi