线程对象在创建后立即销毁?

时间:2015-06-11 00:43:17

标签: c++ multithreading c++11 destructor

我创建了一个类PrimaryThread来处理我主要线程之外的大多数应用程序的工作,它不会受到需要在主线程上工作的代码的干扰,可能是阻塞。我在堆栈中的main()内创建了PrimaryThread对象,然后......它会立即自行销毁。

这是我的main()功能:

int main(int, char**)
{
    Main::running = true;
    cout << "Hello World!\n";

    Config config("config.ini");
    Window window(&config);
    PrimaryThread(&config, &window);
    cout << "  blah\n";

    while(Main::isRunning())
    {
        window.handleMessages();
    }

    cout << "Goodbye World!\n";
    return 0;
}

这里是PrimaryThread类的构造函数和析构函数:

PrimaryThread(Config* config, Window* window)
:   _primaryThread(main, this),
    _config(config),
    _window(window)
{
    if (!_primaryThread.joinable())
    {
        std::cerr << "!Failed to initialize primary thread!\n";
        Main::shutDown();
    }
}

~PrimaryThread()
{
    std::cout << "Destructing PrimaryThread class.\n";
    Main::shutDown();
    _primaryThread.join();
}

PrimaryThread::_primaryThread是一个私有变量,std::thread(不是指针,因此在堆栈上分配)。 PrimaryThread::main()是一个私有方法,其地址被传递给_primaryThread的构造函数。它确实构造并运行了线程。

PrimaryThread::main内的循环依赖于Main::isRunning(),在任何线程调用Main::shutDown()后返回false。如果我注释掉那一行,那么线程就会正常循环,但是主线程被困在一个永远不会结束的冻结中,因为_primaryThread.join()会阻塞它,并且无法接收输入(输入在window.handleMessages()中处理,在主线程上),主线程永远不会从循环中断开。

在没有评论任何行的情况下,我的控制台最终看起来像:

Hello World!
Window opened. // Window::Window(), on main thread
Destructing PrimaryThread class.
Primary thread started // PrimaryThread::main(), on primary thread
primary thread shutting down // as above
  blah
Goodbye World!
Window closed. // Window::~Window(), on main thread

如果我在析构函数中注释掉_primaryThread.join(),我就会崩溃。我不知道为什么,我使用的调试器无法跟踪它,我的控制台显示:

terminate called without an active exception

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

...然后该过程返回3.

这到底是怎么回事?

1 个答案:

答案 0 :(得分:1)

PrimaryThread(&config, &window);创建一个未命名的临时PrimaryThread对象,该对象在;被销毁。

相关问题