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