Question:
Is it possible to assign a new value to a std :: future without getting the result of the previous task?
For instance:
std::future<TResult> f; // глобальная переменная
TResult thread_func(params) { /* тут какие-то тяжелые вычисления */ }
// запрос "долгой" операции (может поступить до окончания предыдущего расчета!)
void RequestAsync()
{
f = std::async<TResult>(thread_func, some_params);
}
// проверяем получение результата (например, таймером)
void CheckResult()
{
if (!f.valid())
return;
TResult result = f.get();
}
I tested this code and did not get any errors, but doubts about the correctness of such an assignment remain. For example, what happens if several running threads return the parameter value at the same time? Will there be a memory leak when a thread tries to return a value through a variable that has already been overwritten by async?
Answer:
You think your code works this way. And, in general, this is logical. Unfortunately, the reality is that the code works differently. This is how this line works:
f = std::async<TResult>(thread_func, some_params);
If f
has a future
stored in a previous async
run, then only after the previous operation completes, a new future
will be placed in f
. Thus, with this approach, there can be no more than 2 simultaneous operations, and it will never be possible to put a new object in f
until the old one has completed.