C++11线程:使用lambda表达式调用时出现异常

4
我正在了解C++11中的线程,我做了一些尝试来创建一个新的线程。
#include <iostream>
#include <thread>

using namespace std;

void doSomething() { cout << "Inside doSomething " << endl; }
void doSomethingElse() { cout << "Inside doSomethingElse " << endl; }

int main(void)
{
    // Using LAMBDA expressions to call the functions.
    thread my_thread([](){ doSomething(); doSomethingElse(); });
    //my_thread.join(); ---------------> 1

    return 0;
}

我尝试执行代码,但没有调用my_thread.join(),Visual Studio 2013报错“abort()已被调用”。 原因是什么?

1个回答

6
这与Lambda表达式无关。如果一个thread在其析构函数执行时是joinable状态,则会调用std::terminate。为了避免这种情况,您必须调用thread::jointhread::detach。标准甚至在备注中提供了这个决定的原因。
来自§30.3.1.3/1 [thread.thread.destr]
 ~thread();

If joinable(), calls std::terminate(). Otherwise, has no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. —end note ]

在早期的C++0x草案中,措辞如下:
如果joinable()为真,则detach(),否则无影响......。 N2802包含了更多关于为什么在析构函数中隐式调用detach()被移除的细节。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接