k_sleep() does not work as described in the documentation #66145
Labels
area: Kernel
bug
The issue is a bug, or the PR is fixing a bug
priority: medium
Medium impact/importance bug
Describe the bug
In the documentation for
k_sleep()
it says that this function returns "Zero if the requested time has elapsed or the number of milliseconds left to sleep, if thread was woken up by k_wakeup call.". Internally it callsz_tick_sleep()
, which returns the number of ticks left to sleep and converts this number to ms using the floor operation (k_ticks_to_ms_floor64()
).When the actual number of milliseconds left to sleep is < 1, it will floor this to 0 and
k_sleep()
returns 0. This conflicts with the description in the documentation, becausek_sleep()
returns 0 although the requested time has not elapsed.Workaround
Use
k_usleep()
to lower the probability that 0 is returned, although the requested time has not elapsed.Alternatively, I think that
CONFIG_SYS_CLOCK_TICKS_PER_SEC
could be set to 1000.To Reproduce
Set a thread to sleep for
n
ms usingk_sleep()
. Then usek_wake()
from another thread aftern - 0.9
ms.k_sleep()
will return 0 although the timer has not elapsed.Expected behavior
If the actual number of milliseconds left to sleep is > 0 but <= 1,
k_sleep()
should return 1. A possible solution would be to change the conversion fromk_ticks_to_ms_floor64()
tok_ticks_to_ms_ceil64()
. Another solution would be to return -1 ink_sleep()
if the requested time has elapsed.It would be also useful to have a function
k_tick_sleep
similar to the internalz_tick_sleep
in order to have more fine-grained control (see #17162).Impact
This is a mayor problem when the code relies on what is returned by
k_sleep()
. There is currently no way to certainly know if the requested time has elapsed. But the documentation states that this should be possible.Environment:
The text was updated successfully, but these errors were encountered: