#include <chrono>
#include <iostream>
#include <future>
void timer() {
std::cout << "Start\n";
for(int i=0;i<10;++i)
{
std::cout << (10-i) << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "DONE\n";
}
int main ()
{
auto future = std::async(timer);
std::cout << "test\n";
}
If the operation performed in timer() takes significant time you can get better accuracy like this:
void timer() {
std::cout << "Start\n";
auto start = std::chrono::high_resolution_clock::now();
for(int i=0;i<10;++i)
{
std::cout << (10-i) << '\n';
std::this_thread::sleep_until(start + (i+1)*std::chrono::seconds(1));
}
std::cout << "DONE\n";
}
Now, using the code in the main() function, it doesn't work for me.
I have to say that after calling the timer code, i enter in a loop that wait for input (cin).
std::this_thread::sleep_for( std::chrono::seconds(3) ) ;
keep_running = false ; // ask he threads to quit
std::this_thread::sleep_for( std::chrono::milliseconds(500) ) ; // give them a bit of time to exit cleanly
Could you give me further informations?
To which thread "this_thread" is referring to, to the main() thread?
setting keep_running=false cause the detach?
std::this_thread is a namespace.
The functions in this namespace are used to manage 'the current thread' - ie. the thread that calls these functions.
When we use std::this_thread::sleep_for( std::chrono::seconds(3) ) ; in main(),
it pauses the execution of main() for at least three seconds.
> setting keep_running=false cause the detach?
No. In the snippet, the thread is detached immediately after creation. std::thread( repeat_print_message, 200, std::ref(keep_running), baba ).detach() ;
keep_running is an atomic boolean flag, passed to the function by reference. void repeat_print_message( unsigned int period_msecs, std::atomic<bool>& keep_running, std::string msg );
std::thread( repeat_print_message, 200, std::ref(keep_running), baba ).detach() ;
In repeat_print_message(), the loop while(keep_running) ends, and the function returns when this flag is false.
Just before exiting from main(), we set the flag to false, and then wait for a little time to let the detached threads terminate gracefully before we end the program by returning from main().