SHARE
TWEET

Untitled

a guest Nov 1st, 2011 87 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <unistd.h>
  2.  
  3. #include <future>
  4. #include <iostream>
  5. #include <string>
  6. #include <sstream>
  7.  
  8. template <typename T> class AsyncResult {
  9. private:
  10.     std::future<T> fut;
  11. public:
  12. #ifdef __BLOCKS__
  13.     AsyncResult(BlockWrapper<T>&& bw) : fut(std::async(std::launch::async, bw)) {}
  14. #else
  15.     AsyncResult(std::function<T()>&& f) : fut(std::async(std::launch::async, f)) {}
  16. #endif
  17.     AsyncResult(AsyncResult&& r) : fut(std::move(r.fut)) {}
  18.     operator T() { return fut.get(); }
  19.     T operator+(T n);
  20. };
  21.  
  22. #ifdef __BLOCKS__
  23. #define LAMBDA(x) BlockWrapper<decltype(x)>(^{ return x; })
  24. #else
  25. #define LAMBDA(x) [=]()->decltype(x){ return x; }
  26. #endif
  27.  
  28. #define ASYNC(x) AsyncResult<decltype(x)>(LAMBDA(x))
  29.  
  30. template <typename T> T AsyncResult<T>::operator+(T n) { return fut.get() + n; }
  31. template <> std::string AsyncResult<std::string>::operator+(std::string n) {
  32.     std::stringstream ss;
  33.     ss << fut.get() << n;
  34.     return ss.str();
  35. }
  36.  
  37. std::string download(const std::string& url) {
  38.     if (url == "BBB")
  39.         sleep(20);
  40.     else
  41.         sleep(15);
  42.     return url;
  43. }
  44.  
  45. void process(const std::string& s) {
  46.     std::cout << s << std::endl;
  47. }
  48.  
  49. int main(void) {
  50.     auto s1 = ASYNC(download("AAA"));
  51.     auto s2 = ASYNC(download("BBB"));
  52.     process(s1 + s2);
  53. }
  54.  
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top