Advertisement
Guest User

work in progress async replacement

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