I implemented a class that loops through the supplied function.
#include <chrono>
#include <mutex>
#include <thread>
class Timer {
public:
Timer(const std::chrono::milliseconds period, const std::function<void()>& handler);
~Timer();
void Start();
void Stop();
bool IsRunning() const;
private:
const std::function<void()>& handler;
const std::chrono::milliseconds period;
bool isRunning = false;
mutable std::recursive_mutex lock;
int counter = 0;
void DoLoop(int id);
};
#include "Timer.h"
Timer::Timer(const std::chrono::milliseconds period, const std::function<void()>& handler) :handler(handler), period(period), lock(){}
Timer::~Timer() {
Stop();
}
void Timer::Stop() {
lock.lock();
isRunning = false;
lock.unlock();
}
void Timer::Start() {
lock.lock();
if (!isRunning) {
isRunning = true;
counter++;
std::thread(&Timer::DoLoop, this, counter).detach();
}
lock.unlock();
}
void Timer::DoLoop(int id) {
while (true){
std::this_thread::sleep_for(period);
lock.lock();
bool goOn = isRunning && counter==id;
if (goOn) std::thread(handler).detach();
lock.unlock();
if (!goOn)
break;
}
}
bool Timer::IsRunning() const {
lock.lock();
bool isRunning = this->isRunning;
lock.unlock();
return isRunning;
}
And here is a simple program to see if it works:
void Tick(){ cout << "TICK" << endl; }
int main() {
Timer timer(milliseconds(1000), Tick);
timer.Start();
cin.get();
}
When I create an application using g ++, the program creates and runs without problems. However, when I use the Microsoft compiler (v18), the program also compiles, but it does not work at run time.
When I use the release configuration, I get the following exception from one of the threads:
Unhandled exception in 0x000007F8D8E14A30 (msvcr120.dll) in Program.exe: exit from a fatal program requested.
When I use the debug configuration, a Microsoft Visual C ++ Runtime Library error occurs every second:
Debug error!
Program: ... \ path \ Program.exe
R6010 - abort()
:
MSVC? - MSVC? , , - ?