For this example, it would certainly make more sense to return a value in the lambda provided to std::async
.
In general, futures and promises are meant to facilitate asynchronous programming. Where waiting should typically be avoided or at least reduced.
To avoid waiting altogether, you could use the experimental std::future::then
to assign a continuation function that will process the result of the first lambda.
Alternatively you could use co_await
which basically wraps std::future::then
behavior in a more readable syntax. But in my opinion it is better if you first have a solid understanding of the std::future::then
mechanism.
To reduce waiting, you can utilize the posting thread (main) to do something useful while the asynchronous task is running in the background.
Note that co_await
is quite new to C++ and supported only on certain compilers.
std::future::then
is still in experimental stages, but available at least on msvc.
As for your specific questions:
Does above snippet presents proper usage of future and promise? (in
theory)
The code will work, but the usage pattern is not ideal as explained.
Will get(), called on line B, block until the thread function
testFunc() has completed and exited?
Yes. It will block until testFunc has completed its work on a background thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…