Update Timer class to accept functions with any number of parameters

This commit is contained in:
2019-01-05 13:27:47 +01:00
parent 7ad040c6c1
commit 4c66aa0831
6 changed files with 77 additions and 17 deletions
+25 -1
View File
@@ -1,6 +1,8 @@
#ifndef UTIL_TIMER_H
#define UTIL_TIMER_H
#include <iostream>
#include <atomic>
#include <functional>
#include <thread>
@@ -15,13 +17,35 @@ public:
Timer();
~Timer();
void Start(int interval, std::function<void(void)> func);
bool operator==(const Timer& other) const;
public:
std::string Identifier() const;
template <typename ...FunctionArguments, typename ...Arguments>
void Start(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
{
if (m_run.load(std::memory_order_acquire))
Stop();
m_run.store(true, std::memory_order_release);
m_thread = std::thread([this, interval, function, arguments ...]()
{
while (m_run.load(std::memory_order_acquire))
{
function(std::forward<Arguments>(arguments)...);
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
});
}
void Stop();
bool IsRunning() const noexcept;
void Wait();
private:
std::atomic<bool> m_run;
std::string m_identifier;
std::thread m_thread;
};