Is there the equivalent of packaged_task :: set_exception?

My assumption is that packaged_task has a promise from below. If my task throws an exception, how do I redirect it to a related future ? With just a promise I could call set_exception - how do I do the same for packaged_task ?

+4
source share
1 answer

An std::packaged_task has an associated std::future object that will contain the exception (or the result of the task). You can get this future by calling the get_future() function from std::packaged_task .

This means that for throw is an exception inside the function associated with the packed task, so that the exception can be caught by the future task (and re-selected when get() is called on the future object).

For instance:

 #include <thread> #include <future> #include <iostream> int main() { std::packaged_task<void()> pt([] () { std::cout << "Hello, "; throw 42; // <== Just throw an exception... }); // Retrieve the associated future... auto f = pt.get_future(); // Start the task (here, in a separate thread) std::thread t(std::move(pt)); try { // This will throw the exception originally thrown inside the // packaged task function... f.get(); } catch (int e) { // ...and here we have that exception std::cout << e; } t.join(); } 
+6
source

All Articles