Let's have a class, which creates a thread and let run an infinite loop checking a que. In this thread, I would like to call periodically a function of the class (to proces accumulated data from the que, for instance each 100 ms).
I've assembled a timer based on aswers http://ift.tt/1BUMItT and http://ift.tt/1we0Bfp However, I do not know, how to call a function from the object, which created the thread. The timer is bellow:
#include <thread>
class TimerSimpleInfinite
{
public:
template <class callable, class... arguments>
TimerSimpleInfinite(int interval, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
execute = true;
std::thread([this, interval, task]()
{
while (execute)
{
task();
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
}).detach();
}
void Cancel()
{
execute = false;
}
private:
bool execute;
};
The idea I would like to achieve is to call the member class function like in the following snippet:
// separated thread
void Processor::Run()
{
// start timer - call member class function every 100 ms
Timer timer(100, this, &Processor::EvaluateData);
Data datata;
while (sharedQueData.Dequeue(data))
{
// preprocess data...
std::lock_guard<std::mutex> lock(mutex);
mVector.insert(data);
}
}
// member class function to be called every 100 ms by timer
void Processor::EvaluateData()
{
std::lock_guard<std::mutex> lock(mutex);
// do anything with mVector
}
The program has to be compiled by VS 2013.
Aucun commentaire:
Enregistrer un commentaire