4

While this question isn't limited to the OpenKinect Libraries, it is the best example I could come up with for showing this off.

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

// 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 simply: is it possible to catch these errors somehow and handle them?

Ordinarily, I would handle the exceptions, or rewrite the code: I don't like having programs crash because of exceptions, I would rather handle them cleanly if I know it is possible for them to occur. There are some libraries that do similar things that I cannot rewrite, hence why I came around to asking this question.

AdmiralJonB
  • 2,038
  • 3
  • 23
  • 27
  • Why can you not handle the exceptions? Why not a try/catch round the '(*freenect)();' call? – Martin James Mar 04 '13 at 15:57
  • The whole point is that this is part of a library. While this one is open source and can be changed, there are other situations that I cannot change it. So I was just wanting to know if it was possible to catch a throw from another thread using pthreads. – AdmiralJonB Mar 04 '13 at 16:42
  • 1
    Not directly, no. Exceptions are a stack-based mechanism and so are thread-specific. If you don't catch them in pthreads, the threads wil be terminated silently. Communicating exceptions to other threads will require inter-thread comms in the catch{}; – Martin James Mar 04 '13 at 19:27

1 Answers1

0

You have to define more clearly what are the thread's responsibilities. I'm guessing it feeds some messages to some other threads, through some kind of pipe or concurrent queue. In that case just change your message class to store exception information (std::exception_ptr). When you access the data in the message, first check if contains an exception; if so, call std::rethrow_exception().

A similar mechanism is used in std::future(); either you get() the promised value out of it, or an exception is raised while trying to do so, that came from the other thread. Search for std::async() examples to see it in action.

DanielKO
  • 4,422
  • 19
  • 29