1

I was told if one thread got some error, the whole process would be stopped. I used the c++11 code as below to do a simple test:

#include <iostream>
#include <thread>
#include <chrono>

void func1()
{
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::cout<<"exception!!!"<<std::endl;
        throw(std::string("exception"));
}

void func2()
{
        while (true)
        {
                std::cout<<"hello world"<<std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(1));
        }
}


int main()
{
        std::thread t1(func1);
        std::thread t2(func2);
        t1.join();
        t2.join();

        return 0;
}

I compiled (g++ -std=c++11 -lpthread test.cpp) and executed it.

5 seconds later, I did get an error: Aborted (core dumped)

In my opinion, each thread has it own stack. In this example, if the stack of t1 dies, why can't the t2 continue?

Yves
  • 11,597
  • 17
  • 83
  • 180

1 Answers1

0

As a thread only has its stack as private, all other things (heap, bss, data, text, env) are shared between threads. One thread crash will lead to the whole process crash, so t1 affected t2 in your program.

Larry.He
  • 604
  • 5
  • 16
  • 1
    Note that there is support for transfering exceptions between threads in C++, see https://stackoverflow.com/questions/233127/how-can-i-propagate-exceptions-between-threads – Erik Alapää Mar 19 '18 at 13:23