我听说“现代操作系统会在关闭进程时清除进程创建的所有线程”,但是当我返回 main()
时,我遇到了这些错误:
1) This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
2) terminate called without an active exception
我的实现看起来像这样(例如,我现在写的是对糟糕的实现感到抱歉):
void process(int id)
{
while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1); } }
}
int main()
{
std::thread thr1(process, 0);
std::thread thr2(process, 1);
//thr1.detach();
//thr2.detach();
return 0;
}
如果我取消注释 detach();
,没有问题,但我的处理线程将是套接字读取器/写入器,它们将无限运行(直到 main 返回)。那么如何处理呢?怎么了?
编辑: 也就是说,我不能一个接一个地分离()每个线程,因为它们不会正常终止(直到结束)。哦,再一次,如果我从 DDOS 窗口的 X 按钮关闭我的程序,(我的简单解决方案在这种情况下不起作用)我的 detach();由于程序强制终止而传递的函数,这里再次出现错误:)
最佳答案
应用程序中发生的事情与操作系统可能做的事情无关。
如果 std::thread
被销毁,仍然有一个可连接的线程,应用程序调用 std::terminate
并且这就是显示的内容:http://en.cppreference.com/w/cpp/thread/thread/~thread `
对于 c++11 线程,如果您不关心它们的完成时间,您可以分离,或者您关心并需要在线程对象被销毁之前加入。
关于C++11 main() 返回时终止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24572731/