Advertisement
Guest User

my async work in progress

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