Reputation:
I was reading about threads in C++11 and I did
#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;
}
I tried to execute the code without calling my_thread.join()
, Visual Studio 2013 is throwing "abort() has been called".
What is the reason?
Upvotes: 4
Views: 573
Reputation: 109149
This has nothing to do with lambdas. If a thread
is joinable
when its destructor executes std::terminate
will be called. To avoid this you must call thread::join
or thread::detach
. The standard even goes on to provide the rationale for this decision in a note.
From §30.3.1.3/1 [thread.thread.destr]
~thread();
If
joinable()
, callsstd::terminate()
. Otherwise, has no effects. [ Note: Either implicitly detaching or joining ajoinable()
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 ]
In early C++0x drafts the wording used to be
If
joinable()
thendetach()
, otherwise no effects. ...
N2802 contains additional details of why implicit invocation of detach()
in the destructor was later removed.
Upvotes: 6