i want to have a timer running in the background of my program while i do other stuff.
My program looks like:
void timer(int number)
{
std::this_thread::sleep_for(std::chrono::seconds(number));
std::cout << "executing someFunction()";
}
int function1()
{
int number = 3;
auto future = std::async(timer, number)
int choice;
std::cout << "please enter a number: ";
std::cin >> choice;
while (choice != 0)
{
std::cout << choice << std::endl;
std::cout << "please enter a number: ";
std::cin >> choice;
}
return 1;
}
int main()
{
int num_rows = function1();
}
Headers are:
#include <iostream>
#include <chrono>
#include <future>
Problem is, after calling the function "timer" with async, it doesn't stop which causes function1 to be stuck as well.
I've understood there is no option to cancel a thread (yet) and to do so I have to pass an "atomic variable" flag to the async task. Could someone please show me an example?
other sources:
c++ background timer (stackoverflow)
is there a way to cancel/detach a future in c++11? (stackoverflow)