【发布时间】:2019-12-28 07:31:50
【问题描述】:
#include <iostream>
#include <string>
#include <thread>
using namespace std;
struct safe_thread : public thread
{
using thread::thread;
safe_thread& operator=(safe_thread&&) = default;
~safe_thread()
{
if (joinable())
{
join();
}
}
};
struct s
{
safe_thread t;
std::string text = "for whatever reason, this text will get corrupted";
s() noexcept
{
std::cout << text << '\n'; // it works in constructor as expected
t = safe_thread{ [this]
{ long_task(); }};
}
void long_task()
{
for (int i = 0; i < 500; ++i)
{
std::cout << text << '\n'; // the text gets corrupted in here
}
}
};
int main()
{
s s;
}
在上面的代码中,text 变量将在构造函数中正确打印。但是,在单独线程中运行的 long_task() 函数中,文本被破坏(它在另一台机器上彻底崩溃)。怎么会这样?如果safe_thread 的析构函数将在struct s 的析构函数中运行,那么thread 和text 的生命周期不应该同样长吗?即当 s 超出main() 的范围时,它们都会超出范围?
【问题讨论】:
-
你真的要制作
s()noexcept吗?如果线程无法启动,std::thread构造函数可以抛出,如果分配失败,std::thread可以抛出std::bad_alloc。
标签: c++ c++11 lifetime stdthread