c++11 - Is there a packaged_task::set_exception equivalent? -
my assumption packaged_task has promise underneath. if task throws exception, how route associated future? promise call set_exception – how do same packaged_task?
an std::packaged_task has associated std::future object hold exception (or result of task). can retrieve future calling get_future() member function of std::packaged_task.
this means enough throw exception inside function associated packaged task in order exception caught task's future (and re-thrown when get() called on future object).
for instance:
#include <thread> #include <future> #include <iostream> int main() { std::packaged_task<void()> pt([] () { std::cout << "hello, "; throw 42; // <== throw exception... }); // retrieve associated future... auto f = pt.get_future(); // start task (here, in separate thread) std::thread t(std::move(pt)); try { // throw exception thrown inside // packaged task's function... f.get(); } catch (int e) { // ...and here have exception std::cout << e; } t.join(); }
Comments
Post a Comment