【发布时间】:2015-08-26 11:53:15
【问题描述】:
我创建了一个类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。
这到底是怎么回事?
【问题讨论】:
-
想必你想要
PrimaryThread thread(&config, &window); -
天哪,我现在感觉自己像个白痴……这正是问题所在,它解决了所有问题。您能否回复一下,以便我将其标记为已回答并给您代表?
-
您从未创建过实际线程。请参阅我上面提供的链接。
-
它实际上确实成功地创建了线程,并且它确实使用类的成员函数运行。那不是问题所在。问题是我实际上并没有创建一个
PrimaryThread对象,我只是在一个“对象”上调用它的构造函数,我不知道,它只在构造函数的持续时间内存在?我不知道为什么它没有给我一个编译器错误。 -
@TimBiegeleisen 你混淆了 Windows 的
CreateThread和 C++11std::thread。
标签: c++ multithreading c++11 destructor