Skip to content

Commit

Permalink
cpp11-compat: thread::sleepfor in microseconds
Browse files Browse the repository at this point in the history
esure sleep
  • Loading branch information
kfessel committed Mar 30, 2023
1 parent 7f95ee7 commit 5f22450
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
24 changes: 14 additions & 10 deletions sys/cpp11-compat/include/riot/thread.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -172,28 +172,32 @@ 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.
*/
template <class Rep, class Period>
void sleep_for(const std::chrono::duration<Rep, Period>& sleep_duration) {
using namespace std::chrono;
if (sleep_duration > std::chrono::duration<Rep, Period>::zero()) {
constexpr std::chrono::duration<long double> max = nanoseconds::max();
nanoseconds ns;
if (sleep_duration > sleep_duration.zero()) {
constexpr duration<long double> max = microseconds::max();
microseconds us;
if (sleep_duration < max) {
ns = duration_cast<nanoseconds>(sleep_duration);
if (ns < sleep_duration) {
++ns;
us = duration_cast<microseconds>(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);
}
}
/**
Expand Down
7 changes: 3 additions & 4 deletions sys/cpp11-compat/thread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint64_t>(duration_cast<microseconds>(ns).count()));
if (us > microseconds::zero()) {
ztimer64_sleep(ZTIMER64_USEC, us.count());
}
}

Expand Down

0 comments on commit 5f22450

Please sign in to comment.