From 90d2ae83fbcb570ff1a59c81bd841b15c4ec1357 Mon Sep 17 00:00:00 2001 From: Karl Fessel Date: Wed, 29 Mar 2023 15:06:59 +0200 Subject: [PATCH] cpp11-compat: thread::sleep_for in microseconds --- sys/cpp11-compat/include/riot/thread.hpp | 24 ++++++++++++++---------- sys/cpp11-compat/thread.cpp | 7 +++---- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/sys/cpp11-compat/include/riot/thread.hpp b/sys/cpp11-compat/include/riot/thread.hpp index 219167268e..bc30048a78 100644 --- a/sys/cpp11-compat/include/riot/thread.hpp +++ b/sys/cpp11-compat/include/riot/thread.hpp @@ -172,9 +172,9 @@ inline thread_id get_id() noexcept { return thread_id{thread_getpid()}; } inline void yield() noexcept { thread_yield(); } /** * @brief Puts the current thread to sleep. - * @param[in] ns Duration to sleep in nanoseconds. + * @param[in] us Duration to sleep in microseconds. */ -void sleep_for(const std::chrono::nanoseconds& ns); +void sleep_for(const std::chrono::microseconds& us); /** * @brief Puts the current thread to sleep. * @param[in] sleep_duration The duration to sleep. @@ -182,18 +182,22 @@ void sleep_for(const std::chrono::nanoseconds& ns); template void sleep_for(const std::chrono::duration& sleep_duration) { using namespace std::chrono; - if (sleep_duration > std::chrono::duration::zero()) { - constexpr std::chrono::duration max = nanoseconds::max(); - nanoseconds ns; + if (sleep_duration > sleep_duration.zero()) { + constexpr duration max = microseconds::max(); + microseconds us; if (sleep_duration < max) { - ns = duration_cast(sleep_duration); - if (ns < sleep_duration) { - ++ns; + us = duration_cast(sleep_duration); + if (us.count() == 0) { + // wait at least 1 + us = microseconds(1); + } + if (us < sleep_duration) { + ++us; } } else { - ns = nanoseconds::max(); + us = microseconds::max(); } - sleep_for(ns); + sleep_for(us); } } /** diff --git a/sys/cpp11-compat/thread.cpp b/sys/cpp11-compat/thread.cpp index f19a41101b..4895b7e745 100644 --- a/sys/cpp11-compat/thread.cpp +++ b/sys/cpp11-compat/thread.cpp @@ -68,11 +68,10 @@ unsigned thread::hardware_concurrency() noexcept { namespace this_thread { -void sleep_for(const chrono::nanoseconds& ns) { +void sleep_for(const chrono::microseconds& us) { using namespace chrono; - if (ns > nanoseconds::zero()) { - ztimer64_sleep(ZTIMER64_USEC, - static_cast(duration_cast(ns).count())); + if (us > microseconds::zero()) { + ztimer64_sleep(ZTIMER64_USEC, us.count()); } }