thread_local 和 std::future 对象 - 对象的生存期是多少
thread_local and std::future object - what is the lifetime of an object?
这是我的测试代码:
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;
}
当foo()
返回时,可以销毁线程 - 以及thread_local
变量。但是由于我使用的是std::future
变量的生存期应该延长,直到调用std::future::get()
,对吧?但在我的情况下,std::future
返回一个空向量。那么规则是什么呢?
但是由于我使用的是 std::future,变量的生命周期应该延长,直到调用 std::future::get((,对吧?
事实并非如此。std::async 使用的线程将在与未来关联的std::promise
上调用set_value()
,然后它可以自由终止。因此,您的线程局部变量很可能在std::future::get()
返回之前甚至在您调用它之前被销毁。
相关文章:
- 对象存在与对象生存期不同吗
- 指向对象生存期之外的已分配内存的指针是"invalid pointer[s]"还是"pointer[s] to an object"?
- QML QQmlPropertyList - 包含的对象生存期和'memory rules'
- 从“if constexpr”分支扩展对象生存期/范围
- 成员重新值引用和对象生存期
- 对象生存期,在这种情况下重用存储
- C++对象生存期优化
- 基于范围的 for 循环的对象生存期问题
- 使用对象生存期运行线程
- C++ Boost.Asio 对象生存期
- 作为参数立即传递的对象生存期是多少
- 智能指针列表-管理对象生存期和指针有效性
- C++标准关于对象生存期的含义是什么
- 如何在 C++11 lambda 中跟踪对象生存期
- C/C++严格的别名、对象生存期和现代编译器
- 如何使用静态强制转换管理共享对象生存期
- 调用了C++对象生存期和析构函数
- 对象生存期内显式构造函数和虚函数调用
- 目标C "autorelease" C++ -- 控制对象生存期的标准方法?
- 具有移动操作和重新值转发的对象生存期