SHARE
TWEET

Untitled

a guest Apr 23rd, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <chrono>
  2. #include <condition_variable>
  3. #include <iostream>
  4. #include <mutex>
  5. #include <thread>
  6.  
  7. using namespace std::chrono_literals;
  8.  
  9. int Func()
  10. {
  11.     std::this_thread::sleep_for(10s);
  12.  
  13.     return 1;
  14. }
  15.  
  16. int FuncWrapper()
  17. {
  18.     std::mutex m;
  19.     std::condition_variable cv;
  20.     int retValue;
  21.  
  22.     std::thread t([&cv, &retValue]() {
  23.         retValue = Func();
  24.         cv.notify_one();
  25.     });
  26.  
  27.     t.detach();
  28.  
  29.     {
  30.         std::unique_lock<std::mutex> l(m);
  31.         if (cv.wait_for(l, 1s) == std::cv_status::timeout)
  32.         {
  33.             throw std::runtime_error("Timeout");
  34.         }
  35.     }
  36.  
  37.     return retValue;
  38. }
  39.  
  40. int main()
  41. {
  42.     bool timedOut = false;
  43.  
  44.     try
  45.     {
  46.         FuncWrapper();
  47.     }
  48.     catch (std::runtime_error& e)
  49.     {
  50.         std::cout << e.what() << std::endl;
  51.         timedOut = true;
  52.     }
  53.  
  54.     if (!timedOut)
  55.     {
  56.         std::cout << "Success" << std::endl;
  57.     }
  58.  
  59.     return 0;
  60. }
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