1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // UNSUPPORTED: libcpp-has-no-threads 10 // UNSUPPORTED: c++03 11 12 // <future> 13 14 // class future<R> 15 16 // template <class Rep, class Period> 17 // future_status 18 // wait_for(const chrono::duration<Rep, Period>& rel_time) const; 19 20 #include <future> 21 #include <cassert> 22 23 #include "make_test_thread.h" 24 #include "test_macros.h" 25 26 typedef std::chrono::milliseconds ms; 27 28 static const ms sleepTime(500); 29 static const ms waitTime(5000); 30 31 void func1(std::promise<int> p) 32 { 33 std::this_thread::sleep_for(sleepTime); 34 p.set_value(3); 35 } 36 37 int j = 0; 38 39 void func3(std::promise<int&> p) 40 { 41 std::this_thread::sleep_for(sleepTime); 42 j = 5; 43 p.set_value(j); 44 } 45 46 void func5(std::promise<void> p) 47 { 48 std::this_thread::sleep_for(sleepTime); 49 p.set_value(); 50 } 51 52 template <typename T, typename F> 53 void test(F func, bool waitFirst) { 54 typedef std::chrono::high_resolution_clock Clock; 55 std::promise<T> p; 56 std::future<T> f = p.get_future(); 57 Clock::time_point t1, t0 = Clock::now(); 58 support::make_test_thread(func, std::move(p)).detach(); 59 assert(f.valid()); 60 assert(f.wait_for(ms(1)) == std::future_status::timeout); 61 assert(f.valid()); 62 if (waitFirst) { 63 f.wait(); 64 assert(f.valid()); 65 t1 = Clock::now(); 66 assert(f.wait_for(ms(waitTime)) == std::future_status::ready); 67 assert(f.valid()); 68 } else { 69 assert(f.wait_for(ms(waitTime)) == std::future_status::ready); 70 assert(f.valid()); 71 t1 = Clock::now(); 72 f.wait(); 73 assert(f.valid()); 74 } 75 assert(t1 - t0 >= sleepTime); 76 } 77 78 int main(int, char**) 79 { 80 test<int>(func1, true); 81 test<int&>(func3, true); 82 test<void>(func5, true); 83 test<int>(func1, false); 84 test<int&>(func3, false); 85 test<void>(func5, false); 86 return 0; 87 } 88