Advertisement
Guest User

myasync work in progress v3

a guest
Apr 16th, 2012
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include <future>
  2. #include <thread>
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6.  
  7. std::string thFun() {
  8.     throw std::exception("bang!");
  9.     return "val";
  10. }
  11.  
  12.  
  13. std::future<std::string> myasync()
  14. {
  15.     auto prms = std::make_shared<std::promise<std::string>> ();
  16.  
  17.     std::future<std::string> fut = prms->get_future();
  18.     std::thread th([=](){
  19.  
  20.         try {
  21.             std::string val = thFun();
  22.  
  23.             prms->set_value(val);
  24.  
  25.         } catch(...) {
  26.             prms->set_exception(std::current_exception());
  27.         }
  28.  
  29.      });
  30.  
  31.     th.detach();
  32.     return fut;
  33. }
  34.  
  35.  int main() {
  36.  
  37.     auto fut = myasync();
  38.    
  39.     try {
  40.         auto res = fut.get();
  41.         std::cout << "Result: " << res << std::endl;
  42.  
  43.     } catch(const std::exception& exc) {
  44.         std::cout << "Exception: " << exc.what() << std::endl; //"Exception: future already retrieved"
  45.     }
  46.  
  47.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement