std::thread 「terminate called without an active exception」

最近在使用std::thread的時候,遇到這樣一個問題:app

std::thread t(func);

若是不使用調用t.join()就會遇到 "terminate called whithout an active exception",可是在使用boost:thread的時候卻沒遇到這個問題,google了一下,找到答案:dom

The trouble you are encountering is a result of the stopThread going out of scope on the stack. The C++ standard has the following to say about this:ui

30.3.1.3 thread destructor [thread.thread.destr]this

~thread();google

If joinable() then terminate(), otherwise 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 ]spa

What this means is that you should not let threads go out of scope without first calling either join() ordetatch().線程

The way you describe it, you want the thread to go out of scope without joining so it will continue to run as your application runs. That requires a call to detach(). From there, I can only offer a little wisdom...debug

大意是說,在~thread();前沒有調用join()則會遇到問題很難調試,若是不想調用join()等線程結束的話你能夠調用detach().這樣就不會遇到"terminate called whithout an active exception"調試

以下:code

{
    std::thread t(func);
    t.detach();
}
相關文章
相關標籤/搜索