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++98, c++03 11 12 // <future> 13 14 // class shared_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 typedef std::chrono::milliseconds ms; 24 25 void func1(std::promise<int> p) 26 { 27 std::this_thread::sleep_for(ms(500)); 28 p.set_value(3); 29 } 30 31 int j = 0; 32 33 void func3(std::promise<int&> p) 34 { 35 std::this_thread::sleep_for(ms(500)); 36 j = 5; 37 p.set_value(j); 38 } 39 40 void func5(std::promise<void> p) 41 { 42 std::this_thread::sleep_for(ms(500)); 43 p.set_value(); 44 } 45 46 int main(int, char**) 47 { 48 typedef std::chrono::high_resolution_clock Clock; 49 { 50 typedef int T; 51 std::promise<T> p; 52 std::shared_future<T> f = p.get_future(); 53 std::thread(func1, std::move(p)).detach(); 54 assert(f.valid()); 55 assert(f.wait_for(ms(300)) == std::future_status::timeout); 56 assert(f.valid()); 57 assert(f.wait_for(ms(300)) == std::future_status::ready); 58 assert(f.valid()); 59 Clock::time_point t0 = Clock::now(); 60 f.wait(); 61 Clock::time_point t1 = Clock::now(); 62 assert(f.valid()); 63 assert(t1-t0 < ms(5)); 64 } 65 { 66 typedef int& T; 67 std::promise<T> p; 68 std::shared_future<T> f = p.get_future(); 69 std::thread(func3, std::move(p)).detach(); 70 assert(f.valid()); 71 assert(f.wait_for(ms(300)) == std::future_status::timeout); 72 assert(f.valid()); 73 assert(f.wait_for(ms(300)) == std::future_status::ready); 74 assert(f.valid()); 75 Clock::time_point t0 = Clock::now(); 76 f.wait(); 77 Clock::time_point t1 = Clock::now(); 78 assert(f.valid()); 79 assert(t1-t0 < ms(5)); 80 } 81 { 82 typedef void T; 83 std::promise<T> p; 84 std::shared_future<T> f = p.get_future(); 85 std::thread(func5, std::move(p)).detach(); 86 assert(f.valid()); 87 assert(f.wait_for(ms(300)) == std::future_status::timeout); 88 assert(f.valid()); 89 assert(f.wait_for(ms(300)) == std::future_status::ready); 90 assert(f.valid()); 91 Clock::time_point t0 = Clock::now(); 92 f.wait(); 93 Clock::time_point t1 = Clock::now(); 94 assert(f.valid()); 95 assert(t1-t0 < ms(5)); 96 } 97 98 return 0; 99 } 100