i have this simple function :
class Timer {
std::atomic<bool> active{true};
public:
void setInterval(auto function, int interval);
void stop();
};
void Timer::setInterval(auto function, int interval) {
active = true;
std::thread t([=]() {
while(active.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
if(!active.load()) return;
function();
}
});
t.detach();
}
void Timer::stop() {
active = false;
}
Now when i try to run it :
int main()
{
printf("start\n");
Timer* timer = new Timer();
timer->setInterval([&]() {
std::cout << "hello" << std::endl;
},1000);
return 0;
};
Only the start printed from the main class , its never reach the function(); inside the setInterval function its just stops the app with no error .
the compile/link command :
/usr/bin/g++ -fdiagnostics-color=always -std=c++14 -pthread -g /home/vagrant/cpp/batch/main.cpp -o /home/vagrant/cpp/batch/main