Prevent the application from crashing if one of the threads crashed

Yur*_*ura 2 c++ multithreading

Is there any way to prevent main thread from crashing?
I want the main thread to keep running after this memory access violation exception happens.

std::thread {
    []() {
        for (auto i = 0; i < 10; ++i) {
            std::cout << "Hello World from detached thread!\n";
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
        std::cout << "Boom!\n";
        *(int*)(0) = 42;
    }
}.detach();

while (true) {
    std::cout << "Hello World!\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
Run Code Online (Sandbox Code Playgroud)

And*_*nle 5

不是一般情况下。

访问冲突的一个主要原因是内存损坏——指向数据元素的指针被覆盖,或者某些对象的大小被擦除。进程中只有一个内存地址空间。new最有可能发生这种情况的地方之一是由、malloc()等人分配的内存堆中。每个进程只有一个堆。

因此,任何破坏内存的线程都会破坏所有线程的内存。

请注意,在您设计的示例中,您知道您正在引用空指针。实际代码中的问题是您永远不会知道为什么要取消引用空指针。如果您非法访问的内存不在地址零或某个非常接近它的值,则某些“杀死该线程以便其余线程可以生存”的逻辑永远无法真正知道发生了什么。

你可以尝试继续跑,就像你可以尝试跑过雷区一样。

如果你继续跑步,你怎么知道你的结果是有效的?几乎可以肯定,您永远不会测试您的进程试图运行的任何确切的内存损坏。因为如果你有的话,你就会知道这个错误并修复它,对吗?

如果你的线程在持有某种锁时死掉了,你会怎么做?