카테고리 없음

std::exception_ptr

newpolaris 2020. 2. 22. 16:30

thread에서 exception 난거 처리안하면 SIGABORT 걸린당

https://www.acodersjourney.com/top-20-cplusplus-multithreading-mistakes/

 ```
    #include <iostream>
    #include <thread>
    #include <exception>
    #include <stdexcept>
    static std::exception_ptr teptr = nullptr;
    void LaunchRocket()
    {
        throw std::runtime_error("Catch me in MAIN");
    }
    int main()
    {
      try
      {
        std::thread t1(LaunchRocket);
        t1.join();
      }
      catch (const std::exception &ex)
      {
        std::cout << "Thread exited with exception: " << ex.what() << "\n";
      }
      return 0;
    }
```

그래서 task/future 등으로 감싸는데, 하나만 처리한다면 단순하게 아래도 된다.

static std::exception_ptr globalExceptionPtr = nullptr;
void LaunchRocket()
{
  try
  {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    throw std::runtime_error("Catch me in MAIN");
  }
  catch (...)
  {
    //Set the global exception pointer in case of an exception
    globalExceptionPtr = std::current_exception();
  }