Is std::exception_ptr thread safe?

There is no special statement about exception_ptr with regards to its thread safety in the standard. As such, it provides the default standard guarantee: accessing separate instances are fine, accessing the same instance is not.

I would suggest using atomic<bool> instead of atomic<exception_ptr> to let the other code know that the exception_ptr has been set. You'll be fine so long as:

  1. You set m_threadException before setting the flag
  2. You read m_threadException after checking the flag
  3. You use the appropriate load/store memory orders to set/check the flag. The defaults are fine
  4. You only write m_threadException exactly once.

The standard doesn't specify what is the implementation of std::exception_ptr, so the thread safeness of std::exception_ptr is also unspecified.

just wrap the exception pointer with some lock and the code will be fine.


Just tried to do this, but std::atomic requires a trivially copyable type, std::exception_ptr is not. You should get compilation error as I do (when using MSVC VS2019, C++14).