SIGABRT 和线程相关的异常,但在调试期间工作正常

SIGABRT and thread related exception but works fine during debug

本文关键字:调试 工作 线程 异常 SIGABRT      更新时间:2023-10-16

下面的代码在运行时会崩溃,但在调试期间工作正常。我不明白为什么。我正在根据需要在析构函数中加入线程。

有人可以帮忙吗?

令人惊讶的是,代码在调试期间工作正常。

在调试中尝试了几次,每次似乎都很好。

#include<iostream>
#include<string>
#include<thread>
#include<memory>
using namespace std;
template<typename T> class Runnable
{
private:
std::thread t;
void runImpl()
{
static_cast<T*>(this)->run();
}
public:
virtual void run() = 0;
void start()
{
this->t = std::thread(&Runnable::runImpl, this);
}
~Runnable()
{
std::cout << "I am in the destructor of the base class" << std::endl;
if(t.joinable())
{
std::cout << "joinable" << std::endl;
t.join();
}
else
std::cout << "not joinable" << std::endl;
}
};
class HelloWorld : public Runnable<HelloWorld>
{
public:
void run()
{
std::cout <<  "I am in thread id = " << std::this_thread::get_id()  << " and the message is : HelloWorld How are you" << std::endl;
}
};
int main(int argc, char* argv[])
{
std::cout << "I am in the main thread id = " << std::this_thread::get_id() << std::endl;
{
HelloWorld item;
item.start();
}
return(0);
}

你在*this上有一个竞争,在调用虚拟成员函数的工作线程和进入析构函数的主线程之间。这表现出未定义的行为。

实际上,vtable 指针可能已经更新为Runnable的指针,线程最终调用了一个纯虚函数。