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

标签 c++ multithreading c++11

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

有人能帮忙吗?

令人惊讶的是,代码在调试期间运行良好。

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

#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/

相关文章:

c++ - 在遍历 vector<> 时获取除第 i 个以外的所有其他元素

c++ - 创建多个 TCP Socket 连接

c++ - QT - 强制对象处理传入信号

C++ Circular #include 前向声明未修复

c++ - 避免空指针

c++ - 在 Visual Studio 中更改(使用旧的)c++ 版本

c++ - 在STL vector 中存储矩阵信息。 vector 或 vector 的 vector 哪个更好?

c++ - 如何在没有函数调用的情况下返回值?

c++ - 模板别名冲突类型。 g++ 编译成功而 clang 失败

java - 线程问题 - 接收方在发送方之前打印