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