Is it possible to prevent a multi-thread application from getting terminated when one of its thread performs an illegal operation like integer divide by zero operation. This is a sample code:
#include <iostream>
#include <thread>
#include <chrono>
void thread1() {
std::this_thread::sleep_for(std::chrono::seconds(2));
for (int i = 3; i >= 0; --i)
std::cout << (3 / i) << std::endl;
std::cout << "thread end" << std::endl;
}
int main() {
std::thread t(thread1);
t.detach();
std::cout << "before sleep\n";
std::this_thread::sleep_for(std::chrono::seconds(5));
//t.join();
std::cout << "after sleep\n";
}
In the above code I'm trying a integer divide by zero operation in a thread which is causing the whole program from getting terminated.
CodePudding user response:
No, in general that isn't possible; all threads in a process share the same memory space, which means that a fatal error in any one thread might have corrupted the data structures of anything else in the process, therefore the whole process is terminated.
If you really need your program to be able to survive a fatal error, then the problematic code needs to be executed inside a separate child process, so that when it crashes, the parent process can survive (and maybe re-launch a new child process, or whatever is appropriate). But in general the preferred approach is simply to make sure that your code doesn't contain any bugs that would lead to crashes.