I wrote a timercallback
class that doesn't run fast enough:
class Manager
{
...
void CallFunction(Function<Treturn>* m_function)
{
do
{
if (m_Status == TimerStatus::Paused)
{
unique_lock<mutex> lock(m_MutexLock);
m_Notifier.wait(lock);
}
while (m_Status != TimerStatus::Stoped&&m_Status != TimerStatus::Paused)
{
unique_lock<mutex> lock(m_MutexLock);
m_Notifier.wait_for(lock, m_Interval);
(*m_function)();
}
} while (m_Status == TimerStatus::Paused);
}
...
}
When I set the time of timercallback to call the function every 1ms it doesn't work. It takes more, for example 10 ms. I need help to improve the code to call the callback function (event function of this timer) in 1 ms intervals and run in one thread with lock. How can I do this?
Sample of use this class:
Manager tester;
TimerCallback<microseconds> m_timer(chrono::microseconds(10), Core::Utility::ptr_fun(&tester, &Manager::runner));
You are trying to use the
wait_for()
function as a timer which is really not a good way to have a high precision timer. If you need the mutex functionality, though, that's pretty much all you'll get.If you use the mutex to get signals, then maybe you could switch to using
ppoll()
. The function can also be used without any events, with just a timeout, then it works as a timer.Another solution is to simply use the
nanosleep()
function. This is much simpler than theppoll()
call since all you need is atimespec
structure:Side note:
From my experience with VirtualBox, a VM clock precision is abysmal. In other words, you are very unlikely to get a reliable 1ms sleep between calls on such a system. I do not know whether that applies to Cloud based VMs (which probably use better solutions than VirtualBox, but probably are in a similar situation with timers).