I need to wait in my program for a subsystem. In different places a have to wait for different conditions. I know I could also make use of threads and conditions variables. But since the subsystem (bare metal programmed in C) is connected via shared memory with no interrupts registered to it -- one thread needs to poll anyways.
So I did the following template to be able to wait for anything. I was wondering whether there is already a STL function which could be used for that?
#include <chrono>
#include <thread>
//given poll interval
template<typename predicate,
typename Rep1, typename Period1,
typename Rep2, typename Period2>
bool waitActiveFor(predicate check,
std::chrono::duration<Rep1, Period1> x_timeout,
std::chrono::duration<Rep2, Period2> x_pollInterval)
{
auto x_start = std::chrono::steady_clock::now();
while (true)
{
if (check())
return true;
if ((std::chrono::steady_clock::now() - x_start) > x_timeout)
return false;
std::this_thread::sleep_for(x_pollInterval);
}
}
//no poll interval defined
template<typename predicate,
typename Rep, typename Period>
bool waitActiveFor(predicate check,
std::chrono::duration<Rep, Period> x_timeout)
{
auto x_start = std::chrono::steady_clock::now();
while (true)
{
if (check())
return true;
if ((std::chrono::steady_clock::now() - x_start) > x_timeout)
return false;
std::this_thread::yield();
}
}
2019-05-23: Code update regarding the comments and answers