If an exception occurs in an asynchronous thread, how do you wait for the expected thread to know and handle the exception correctly?
Suppose you have a function that looks like the square root:
Double Square_root (double x) { if (x<0) { throw std::out_of_range ("x<0"); } return sqrt (x);}
Typically, if you call Square_root () in the context of the current thread, the method is as follows:
Double Y=square_root (-1);
Call Square_root () in the asynchronous thread as follows:
Std::future<double> F=std::async (square_root,-1);d ouble y=f.get ();
Ideally, both methods can obtain the execution result of a function call through Y. If an exception occurs, it is even better to let the caller know about the exception.
In fact, if the function executed in Std::async throws an exception, the exception will be stored in the desired state, expected to become ready, waiting for Get () the thread to be suspended will be awakened, and the Get () function throws the exception stored in the expectation again.
Similarly, std::p Romise also has a similar function, except that we need to display the set_exception () interface to set:
Try{some_promise.set_value (Calculate_value ());} catch (...) {some_promise.set_exception (std::current_exception ());}
This uses std::current_exception () to get the currently thrown exception. In addition, you can use Std::copy_exception () to generate a new exception directly into the promise:
Some_promise.set_exception (Std::copy_exception (Std::logic_error ("foo"));
This is recommended in cases where the exception type is determined, because it is not only clearer than the Try/catch block, and the compiler works better when optimizing the code.
So far, all the sample code is using Std::future, but Std::future has a certain limit, because only one thread can wait for the expected return. If there are multiple threads that need to wait for the same event, we need to use std::shared_future.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[c++11 Concurrent Programming] 16 saving exceptions in expectation