下面的代码在运行时会出错,但在调试时工作正常。我不明白为什么。我根据需要在析构函数中加入线程。
有人能帮忙吗?
令人惊讶的是,代码在调试期间运行良好。
在调试中尝试了几次,每次似乎都很好。
#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
的指针,线程最终调用纯虚函数。
关于c++ - SIGABRT 和线程相关的异常,但在调试期间工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51852971/