Is it possible to assign a new value to the std :: future object without getting the result of the previous task?

For example:

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 will happen if several running threads return a parameter value at the same time? Will there be a memory leak when the thread tries to return a value through a variable already rewritten by async?

    1 answer 1

    That you think your code works that way. And, in general, it 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 saved to the future previous run of async , then only after the previous operation is completed, the new future object will be placed in f . Thus, with this approach, no more than 2 simultaneous operations can be performed, and a new object can never be placed in f until the old one is completed.

    • Thanks for the answer, though, I already figured it out yesterday, looking at the code operator = () from the future) As a result, I had to create a list from future objects, and in the timer check them with valid () and wait_for (0) and then delete it. In general, the future was very disappointing, I think, the task initially had to be solved through ordinary mutexes. - Aleksey Sokolov
    • @AlekseySokolov, c std::future there are no problems, problems are std::async . If you do not use it, then there will be no such problems. - ixSci