Search code examples
c++c++11promisefutureboost-thread

Is there a way to catch the exception thrown from boost::promise when setting it while it's already set?


I have a program that uses a timer to set some double buffer in a GUI application. Under some rare circumstances, e.g., while the program is shutting down, I get an error that the promise that sets this buffer is already set. Is there a way to catch that error and deal with it?

Here's a minimal example:

#include <iostream>
#include <boost/thread/future.hpp>

int main()
{
    boost::promise<int> promise;
    try {
        promise.set_value(0);
        promise.set_value(0);
    } catch (...) {
        promise.set_exception(boost::current_exception());
    }
    return 0;
}

No matter how I try to catch it, it terminates my program with error:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::promise_already_satisfied> >'

And here you can see it in action.


Solution

  • After set_value another set_value fails and I bet the set_exception in your catch block fails with the same reason: the result (either value or exception) is already set, the promise is already satisfied. At least that is how std::promise works and I would not be surprised if boost::promise works the same.