Deleting std::thread pointer raises exception “libc++abi.dylib: terminating”

断了今生、忘了曾经 提交于 2019-12-01 19:03:14

问题


In C++ 11 with LLVM 6.0 on Mac OS X, I first created a pointer to a memory allocation of std::thread.

std::thread* th = new std::thread([&] (int tid) {
    // do nothing.
}, 0);

Then I tried to delete it.

delete th;

However, compiling the above code and execute it raises exception

libc++abi.dylib: terminating
Abort trap: 6

回答1:


The thread you've created is joinable, and unless you join or detach it, std::terminate will be called when the destructor of the thread object executes. So you need

th->join();
delete th;

Early proposals for std::thread implicitly detached the thread in the destructor, but this was found to cause problems when the owning thread threw an exception between creation and joining of a thread instance. N2802 contains the change proposal along with illustrative examples.

The original behavior was carried over from boost::thread but it too has since deprecated implicit detach in the destructor.


Unrelated to your problem, but it is very unlikely you need to dynamically allocate the thread object, and even if you do, you should be storing it in a unique_ptr.



来源:https://stackoverflow.com/questions/25397874/deleting-stdthread-pointer-raises-exception-libcabi-dylib-terminating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!