I start learning about std::thread and std::future, and wrote very trivial example (I wanted to get the value from std::future before std::thread ends):
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int foo(int a, int b)
{
return a + b;
}
int main()
{
auto task = std::packaged_task<int (int, int)>{foo};
auto future = task.get_future();
auto t = std::thread{
[&task](int a, int b)
{
using namespace std::chrono_literals;
task(a, b);
std::this_thread::sleep_for(5s); // something heavy to do
std::cout << "Thread ends.\n";
}, 1, 2
};
std::cout << future.get() << '\n';
std::cout << "Waiting for thread\n";
t.join();
return 0;
}
Fisrtly, I wonder, if a real world example may be something like: logging, or saving something into database.
And secondly, if I cut out the std::this_thread::sleep_for(5s), is there any point of using std::thread instead of std::async?