c ++线程赋值抛出SIGSEGV

时间:2014-03-17 18:37:57

标签: c++ multithreading c++11

我确定我只是做了一些愚蠢的事,但我似乎无法确定它。我正在尝试编写一个类,它将成为我们应用程序中模块的框架。每个模块都有一个消息队列,然后在其自己的线程中处理这些消息。问题是当我调用run()时,线程创建和对成员变量的赋值会导致SIGSEGV。我如何正确地将新线程分配给类的成员变量?

编辑:发布了新的测试用例

class TestModule
{
public:
    TestModule(){}
    virtual ~TestModule(){}

    void run()
    {
        // create the thread
        thrd = std::move(std::thread(&TestModule::_run, this));
    }

protected:
    std::thread thrd;                       // the running thread

private:
    void _run()
    {
        while (!true) {
            sleep(5);   // pretend to do stuff
        }
    }
};

class SimpleApp : public TestModule
{
public:
    ~SimpleApp() {}
};

int main() {
    SimpleApp app;
    app.run();

    int ctr=0;
    while (true) {
        sleep(1);
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

将所有代码移动到一个简单的test.cpp文件后,我注意到Casey,它在没有seg错误的情况下工作得很好。

所以我开始一次解开生产代码。看来,我链接到的第三个库(我们使用各种数据库函数和字符串函数等的实用程序库)是单线程构建的。一旦我用-pthread重建了该库,并重新链接到这个应用程序,崩溃就停止了。

答案 1 :(得分:0)

如果你没有std::thread

std::terminate会致电join()。 查看this answer了解详情。 因此,

void TestModule::run()
{
    // what do we need to do before moving on?
    bNeedsToQuit = false;

    // create the thread
    thrd = std::move(std::thread(&TestModule::_run, this));
    thrd.join();
}