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?
But since I'm using a std::future the lifetime of the variable should be prolonged until the call to std::future::get(), right?
That's not the case. The thread used by std::async will call set_value()
on the std::promise
associated with the future, and then it's free to terminate. Therefore, your thread-local variable may well be destroyed before std::future::get()
returns or even before you call it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.