1

I am storing C++ futures in a map, but then I can't call future::get() on the futures once they are in the map.

Code is:

#include <iostream>
#include <map>
#include <cstdlib>
#include <future>

using namespace std;

int my_func(int x) {
    return x;
}

int main()
{
    map<int, future<int>> tasks;

    // Create a task and add it to the map
    int job_no = 0;
    tasks.insert(make_pair(job_no, async(&my_func, job_no)) );

    // See if the job has finished
    for (auto it = tasks.cbegin(); it != tasks.cend(); ) {
        auto job = it->first;
        auto status = (it->second).wait_for(chrono::seconds(5));

        if (status == future_status::ready) {
           int val = (it->second).get();  /* This won't compile */
           cout << "Job " << job << " has finished with value: " << val << "\n";
           it = tasks.erase(it);
        }
    }

    return 0;
}

The compiler error is:

test.cc:26:39: error: passing ‘const std::future<int>’ as ‘this’ argument discards qualifiers [-fpermissive]
            int val = (it->second).get();  /* This won't compile */
                                       ^
In file included from test.cc:4:0:
/usr/include/c++/7/future:793:7: note:   in call to ‘_Res std::future<_Res>::get() [with _Res = int]’
       get()

I think this has something to do with futures not being callable (eg. see this post and this post), but don't know how to fix it.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
John
  • 451
  • 7
  • 17

1 Answers1

8

The issue is that you are using const-iterator while iterating your map, then you can only read value of map (you can call const memebers on future). But you are calling get on future objects, and you get errors because get is non-const qualified member of future class. So try

for (auto it = tasks.begin(); it != tasks.end(); ) {
rafix07
  • 20,001
  • 3
  • 20
  • 33