Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception between threads. How many std::exception_ptr and synchronization I need?

I am a bit confused, but my question is simple.

I have a bunch of threads, I want to centralize error handling by treating all exceptions in the main thread after sent by other threads.

  1. Do I use a shared exception_ptr global and use std::current_exception() in every catch clause in every thread? Or do I need to have different excpetion_ptr objects for different threads? I would like to keep all exceptions.
  2. once the current_exception is assigned to an exc_ptr variable, when I access the exc_ptr from the main thread, do I need to synchronize the read from the main thread?
like image 497
Germán Diago Avatar asked Sep 04 '26 17:09

Germán Diago


1 Answers

You want to propagate to the main thread only those exceptions that are not handled by the subordinate thread. This means you only need to use exception_ptr at the very top level handler of the subordinate thread.

I think the easiest approach is to have a global container (e.g. a producer/consumer queue) of exception_ptrs. Each top-level thread exception handler pushes its exception to the queue and exits. The main handler pulls exceptions from the queue and rethrows. Of course you need a proper synchronisation for the queue. Once you pull an exceoption_ptr off the queue you don't need to synchronize it, because the thread that has created it won't touch it any more.

It should also be possible to have a single global exception_ptr (equivalent to a queue of capacity 1, and synchronised in much the same way).

like image 180
n. 1.8e9-where's-my-share m. Avatar answered Sep 07 '26 09:09

n. 1.8e9-where's-my-share m.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!