Eliminating exceptions with Pthreads

Although this question is not limited to OpenKinect libraries, this is the best example I could offer to show this.

In C ++ Wrapper for OpenKinect, when something goes wrong, it throws a runtime_error exception. This example is from libfreenect.hpp. The thread is created in the class constructor.

// Do not call directly, thread runs here void operator()() { while(!m_stop) { if(freenect_process_events(m_ctx) < 0) throw std::runtime_error("Cannot process freenect events"); } } static void *pthread_callback(void *user_data) { Freenect* freenect = static_cast<Freenect*>(user_data); (*freenect)(); return NULL; } 

My question is simple: is it possible to somehow catch these errors and handle them?

Normally, I would handle exceptions or rewrite the code: I do not like the failure of programs due to exceptions; I would rather handle them if I knew that this was possible for them. There are several libraries that do similar things that I cannot rewrite, so why did I come to ask this question.

+4
source share
1 answer

You need to more clearly define what are the responsibilities of the flows. I assume that it sends some messages to other threads, through some channel or parallel queue. In this case, just change your message class to store exception information (std :: exception_ptr). When you access data in a message, first check to see if it contains an exception; if so, call std :: rethrow_exception ().

A similar mechanism is used in std :: future (); either you get () the promised value, or an exception occurs when you try to do this, coming from another thread. Search for std :: async () examples to see them in action.

0
source

All Articles