I have a C++ program imposing a memory limit via setrlimit. Depending on the parameters it may throw std::bad_alloc at various locations which I want to handle.
I use multiple threads via std::thread. I have some code along the lines of this:
std::thread* worker; try { worker=new std::thread[NUM_THREADS]; for(int i=0;i<NUM_THREADS;++i) { worker[i]=std::thread(&ThisClass::SomeMemberFunc, this, SomeArg...); } } catch(...) { std::cout << "exception in thread creation" << std::endl; } So thread creation is wrapped in try/catch. Yet it happens that the program abort with:
terminate called after throwing an instance of 'St9bad_alloc' what(): std::bad_alloc When I use gdb and set a breakpoint at abort(), the backtrace looks like:
#0 __GI_abort () at abort.c:53 #1 0x00007ffff717269d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #2 0x00007ffff7170846 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #3 0x00007ffff7170873 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #4 0x00007ffff7127cfb in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #5 0x00007ffff73c2e9a in start_thread (arg=0x7ffff3e86700) at pthread_create.c:308 #6 0x00007ffff6bd93fd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:112 #7 0x0000000000000000 in ?? () Now, how is this possible?
coutthrows?SomeMemberFuncin the newly created thread, not from the thread constructor itself. Can you wrap the body ofSomeMemberFuncinto a try-catch block?std::vector<std::thread>instead ofstd::thread *.std::async(std::launch::async, ...)instead ofstd::thread. With the former, you can catch the exception also on the call-side.