test_cxx_std_future.cpp 880 B

123456789101112131415161718192021222324252627282930
  1. #include <iostream>
  2. #include <future>
  3. #include <thread>
  4. #include "unity.h"
  5. #if __GTHREADS && __GTHREADS_CXX0X
  6. TEST_CASE("C++ future", "[std::future]")
  7. {
  8. // future from a packaged_task
  9. std::packaged_task<int()> task([]{ return 7; }); // wrap the function
  10. std::future<int> f1 = task.get_future(); // get a future
  11. std::thread t(std::move(task)); // launch on a thread
  12. // future from an async()
  13. std::future<int> f2 = std::async(std::launch::async, []{ return 8; });
  14. // future from a promise
  15. std::promise<int> p;
  16. std::future<int> f3 = p.get_future();
  17. std::thread( [&p]{ p.set_value_at_thread_exit(9); }).detach();
  18. std::cout << "Waiting..." << std::flush;
  19. f1.wait();
  20. f2.wait();
  21. f3.wait();
  22. std::cout << "Done!\nResults are: "
  23. << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
  24. t.join();
  25. }
  26. #endif