[英]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. 当
foo()
返回时,可以将线程与thread_local
变量一起销毁。 But since I'm using a std::future
the lifetime of the variable should be prolonged until the call to std::future::get()
, right? 但是,由于我使用的是
std::future
,因此该变量的寿命应延长到调用std::future::get()
,对吧? But in my case the std::future
returns an empty vector. 但是在我的情况下,
std::future
返回一个空向量。 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?
但是由于我使用的是std :: future,因此该变量的寿命应延长到调用std :: future :: get()之前,对吧?
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. std :: async使用的线程将在与将来关联的
std::promise
上调用set_value()
,然后可以自由终止。 Therefore, your thread-local variable may well be destroyed before std::future::get()
returns or even before you call it. 因此,您的线程局部变量很可能在
std::future::get()
返回之前甚至在您调用它之前就被销毁了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.