How to Use Std::Async Without Waiting for the Future Limitation

do I have to call get or wait on a std::async future

Put attention, that destructor of returned future object will perform blocking wait until your task action will finish (and the corresponded shared state will become ready).

See last paragraph on the page: https://en.cppreference.com/w/cpp/thread/future/~future

What Limitation of std::async is Stroustrup Referring To?

The "problem" with std::async is that by default you don't know whether or not it starts a thread. If your function needs to run on a separate thread then this is a problem as your function might not run until get() or wait() is called.
You can pass std::launch::async to ensure the function is launched on its own thread, which is like a std::thread that cannot BG e detached.

Clean-up a timed-out future

My question is, in the case where the future read timed out, do I have to handle the clean-up of the future separately (i.e. keep a copy and check if it is ready time-to-time)? or can I simply ignore it (i.e. keep the code as is).

From my personal perspective, it depends on what you want. Under your current (minimal) implementation, the getValue function will be blocked by the future's destructor(see cppreference page and some SO questions).

If you do not want the blocking behavior, there are some solutions, as proposed in this question, like:

  1. move the future to some outside scope
  2. use a detached executor and some handy code/data structure to handle the return status
  3. see if you can replace the future with some timeout support I/O operations like select/poll

etc.

Return value by value without waiting all values to return async C#

What we did we split our call in two calls. First we called API for id and loaded our page. We not fetched all data so it loaded fast. Second we called API for each id we get and just added data to object from first call. We use data from calls for dropdown element so till second call were finished we still can display object id in dropdown.

How to use std future and async with threading in a for loop with a shared resource as param?

First - define what information each thread shall provide.

In this case - it is probably something like this:

struct Result
{
error_codes::NPPCoreErrorCode error;
float produced_energy;
};

So your future type is std::future<Result>.

Then start your work in many threads:

std::vector<std::future<Result>> results;
for (const auto& core_it : reactor_cores_)
{
auto action = [&]{
Result res;
res.error = core_it.GenerateEnergy(energy_required_per_core, res.power_generated);
return res;
};
// start thread
results.emplace_back(std::async(std::launch::async, action));
}

Then wait for each thread to finish:

  for (auto& f : results) f.wait();

Then, I guess, you want to sum up:


for (auto& f : results) {
Result res = f.get();
if (res.error == error_codes::success)
power_generated += res.power_generated;
else {
power_plant_error_code = res.error;
// depending on your error strategy, you might break here
break;
}
}

Read more here.

scope block when use std::async in function other than the main function

This QUESTION answered in :

main thread waits for std::async to complete

Can I use std::async without waiting for the future limitation?

Whoever, If you store the std::future object, its lifetime will be extended to the end of main and you get the behavior you want.

void printData() 
{
for (size_t i = 0; i < 5; i++)
{
std::cout << "Test Function" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}

std::future<void> runningAsync()
{
return std::async(std::launch::async, test);
}

int main()
{
auto a = runningAsync();

std::cout << "Main Function" << std::endl;
}

That's a problem because std::future's destructor may block and wait for the thread to finish. see this link for more details

std::future returned from std::async hangs while going out of scope

Taking from cppreference sample, only "the start", "f2 finished" and "the end" will get printed from this code (because f1 doesn't "hang"):

#include <future>
#include <thread>
#include <iostream>

int main() {
using namespace std::literals;

{
std::packaged_task<int()> task([]() {
std::this_thread::sleep_for(5s);
std::cout << "f1 finished" << std::endl;
return 42;
});
std::future<int> f1 = task.get_future();
std::thread(std::move(task)).detach();

std::future<int> f2 = std::async(std::launch::async, []() {
std::this_thread::sleep_for(3s);
std::cout << "f2 finished" << std::endl;
return 42;
});

f1.wait_for(1s);
f2.wait_for(1s);
std::cout << "the start" << std::endl;
}

// std::this_thread::sleep_for(7s);
std::cout << "the end" << std::endl;
}

For good discussion see: http://scottmeyers.blogspot.com.br/2013/03/stdfutures-from-stdasync-arent-special.html.

C++ standard library gives no support for thread kill operations.

Take care with threads you detach. Detachment per se is not "extremely bad", it may be useful in user terminable daemons for example, or if you have some other idea of orchestration and teardown. Otherwise, detach would have no point being provided by the standard library.



Related Topics



Leave a reply



Submit