Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <future>
- #include <thread>
- #include <iostream>
- #include <string>
- #include <vector>
- std::string thFun() {
- throw std::exception("bang!");
- return "val";
- }
- std::future<std::string> myasync()
- {
- auto prms = std::make_shared<std::promise<std::string>> ();
- std::future<std::string> fut = prms->get_future();
- std::thread th([=](){
- try {
- std::string val = thFun();
- prms->set_value(val);
- } catch(...) {
- prms->set_exception(std::current_exception());
- }
- });
- th.detach();
- return fut;
- }
- int main() {
- auto fut = myasync();
- try {
- auto res = fut.get();
- std::cout << "Result: " << res << std::endl;
- } catch(const std::exception& exc) {
- std::cout << "Exception: " << exc.what() << std::endl; //"Exception: future already retrieved"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement