Hello All,
I am having one doubt about how `std::async(), std::future and std::promise` works. If you run below code then you will find that even though you set a `promise` value before sleep, still `future.get()` in main thread waits for async thread to finish completely then how it is different from normal functionality of launching a thread and then collect the result after `thread.join()` ?
void CalcSqrt(int no, std::promise<int>& promise)
{
cout << "Inside CalcSqrt..." << endl;
promise.set_value(sqrt(no));
cout << "About to sleep for 100 secs..." << endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
return;
}
int main()
{
cout << "Launching thread from main..." << endl;
std::promise<int> promise;
std::future<int> future(promise.get_future());
std::async(std::launch::async, CalcSqrt, 100,
std::ref(promise));
//std::thread t(CalcSqrt, 100, std::ref(promise));
cout << "Square root of 100 is " << future.get() << endl;
return 0;
}
But if you replace std::async with std::thread then you can clearly see the advantage of using std::promise as future.get() get's value set by promise even before CalcSqrt() comes out of wait. Why it is so ?
Aucun commentaire:
Enregistrer un commentaire