#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()
函数中,该文本会被损坏(在另一台机器上直接崩溃)。为什么会这样?如果在struct s
的析构函数中运行safe_thread
的析构函数,那么thread
和text
的生命周期不应该同样持续很长时间吗?也就是说,当在main()
处离开s的作用域时,它们都将离开作用域?
s()
成为noexcept
吗?如果线程无法启动,std::thread
构造函数可能会抛出异常,如果分配失败,std::thread
也可能会抛出std::bad_alloc
异常。 - walnut