我有一個C++程序通過setrlimit強加內存限制。根據參數,它可能會在我想要處理的各個位置上拋出std :: bad_alloc。無法捕獲由std :: thread構造函數拋出的異常
我使用多個線程通過std :: thread。我有一些代碼沿着這條線:
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;
}
所以線程創建包裹在try/catch中。然而,它發生,該方案與中止:
terminate called after throwing an instance of 'St9bad_alloc'
what(): std::bad_alloc
當我使用GDB和中止(設置斷點),回溯看起來像:
#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 ??()
現在,這怎麼可能?
如果寫入'cout'會拋出什麼? –
我看起來好像在新創建的線程中從'SomeMemberFunc'拋出異常,而不是從線程構造函數本身拋出異常。你可以將'SomeMemberFunc'的主體包裝到try-catch塊嗎? – nosid
不是答案,而是使用'std :: vector'而不是'std :: thread *'。 –
Chnossos