On 2024-08-06 at 17:17 +0200, Bash-help via Bug reports for the GNU
Bourne Again SHell wrote:
> #!/bin/bash
> 
> while true; do
>     SECONDS=0
>     sleep 0.5
>     if [ "$SECONDS" != "0" ]; then
>         printf 'This is unexpected: %s != 0\n' "$SECONDS"
>     fi
> done
> 
> As we sleep less than a full second the expanded value of SECONDS
> should never be greater than 0 but it sometimes is. I guess this is
> because the assignment might occur, say X.7 seconds and the expanded
> value will then read (X+1).2 which would be rounded down to (X+1).

Please note that the contract with the OS is to sleep *at least* half a
second. You have no guarantee that it won't sleep more. Typically,
after half a second the process will return to the list of programs
ready to be executed, and get a time slot depending on the number of
processes ready, the system load, etc.

In POSIX description of sleep(2):

> The suspension time may be longer than requested due to the
scheduling of other activity by the system.

https://pubs.opengroup.org/onlinepubs/9699919799/functions/sleep.html


For big values such as 0.5, that delay is unlikely to be relevant, but
one should not assume the sleep will be exactly the specified amount
and no more.

Regards





Reply via email to