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 // ALLOW_RETRIES: 3
13 
14 // <future>
15 
16 // class future<R>
17 
18 // template <class Rep, class Period>
19 //   future_status
20 //   wait_for(const chrono::duration<Rep, Period>& rel_time) const;
21 
22 #include <future>
23 #include <cassert>
24 
25 #include "make_test_thread.h"
26 #include "test_macros.h"
27 
28 typedef std::chrono::milliseconds ms;
29 
30 static const ms sleepTime(500);
31 static const ms waitTime(5000);
32 
33 void func1(std::promise<int> p)
34 {
35   std::this_thread::sleep_for(sleepTime);
36   p.set_value(3);
37 }
38 
39 int j = 0;
40 
41 void func3(std::promise<int&> p)
42 {
43   std::this_thread::sleep_for(sleepTime);
44   j = 5;
45   p.set_value(j);
46 }
47 
48 void func5(std::promise<void> p)
49 {
50   std::this_thread::sleep_for(sleepTime);
51   p.set_value();
52 }
53 
54 template <typename T, typename F>
55 void test(F func, bool waitFirst) {
56   typedef std::chrono::high_resolution_clock Clock;
57   std::promise<T> p;
58   std::future<T> f = p.get_future();
59   Clock::time_point t1, t0 = Clock::now();
60   support::make_test_thread(func, std::move(p)).detach();
61   assert(f.valid());
62   assert(f.wait_for(ms(1)) == std::future_status::timeout);
63   assert(f.valid());
64   if (waitFirst) {
65     f.wait();
66     assert(f.valid());
67     t1 = Clock::now();
68     assert(f.wait_for(ms(waitTime)) == std::future_status::ready);
69     assert(f.valid());
70   } else {
71     assert(f.wait_for(ms(waitTime)) == std::future_status::ready);
72     assert(f.valid());
73     t1 = Clock::now();
74     f.wait();
75     assert(f.valid());
76   }
77   assert(t1 - t0 >= sleepTime);
78 }
79 
80 int main(int, char**)
81 {
82   test<int>(func1, true);
83   test<int&>(func3, true);
84   test<void>(func5, true);
85   test<int>(func1, false);
86   test<int&>(func3, false);
87   test<void>(func5, false);
88   return 0;
89 }
90