Advertisement
Guest User

myasync v5

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