mercredi 5 avril 2017

thread_local and std::future object - what is the lifetime of an object?

Here's my test code:

vector<int> const & foo(int const counter)
{
    thread_local static vector<int> v{counter, counter + 1, counter + 2};
    return v;
}

int main()
{
    using myFut = future<vector<int> const &>;

    vector<myFut> futures;
    for(int i{0}; i < 5; ++i)
    {
        futures.push_back(async(launch::async, &foo, i * 3));
    }

    for(myFut & fut : futures)
    {
        vector<int> v{fut.get()}; // or vector<int> const & v{fut.get()};
        cout << v.size() << endl; // 0, I expect 3
    }

    return 0;
}

When foo() returns a thread can be destroyed - together with a thread_local variable. But since I'm using a std::future the lifetime of the variable should be prolonged until the call to std::future::get(), right? But in my case the std::future returns an empty vector. So what are the rules?

Aucun commentaire:

Enregistrer un commentaire